﻿using _698._45Tool.Utils;
using CommonServiceLocator;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using Jn698._45GWTool.Common;
using Jn698._45GWTool.Communication;
using Jn698._45GWTool.Controls;
using Jn698._45GWTool.Models;
using Jn698._45GWTool.Models.DataGrid;
using Jn698._45GWTool.ServiceReference1;
using Jn698._45GWTool.Services;
using Jn698._45GWTool.Settings;
using Jn698._45GWTool.ViewModels.Controls.DataControls;
using Jn698._45GWTool.Views;
using Jn698._45Tool.Service;
using Jn698._45Tool.Utils;
using nblTool.utils;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Routing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using TouchMvvm;
using TouchSocket.Core;
using WebFirst.Entities;
using WindowsFormsApp1.Utils;
using static Communication.MessageGenerationModule;


namespace Jn698._45GWTool.ViewModels.Controls
{
    public class AppControlViewModel : ViewModelBase
    {
        private SendModule SendModule = SendModule.Instance;
        private SerialPortHelper serialPortHelper = SerialPortHelper.Instance;
        private TcpHelper tcpHelper = TcpHelper.Instance;
        private ClassIdService classIdService = new ClassIdService();
        private GWCmdMakeUpService gWCmdMakeUpService = new GWCmdMakeUpService();
        private ObjectIDService objectIDService = new ObjectIDService();
        #region 属性
        private object RequestMode = null;
        CancellationTokenSource cts = null;
        private Task MainTask = null;
        //private Dictionary<int, ObjectID> map;
        private List<GWCmdMakeUp> gWCmdMakeUps = new List<GWCmdMakeUp>();
        private GWCmdMakeUp gWCmdMakeUpSelected;
        public static string ESAMDiv;
        public static string ESAMVersion;
        public static string ESAMCounter;
        public static string SessionInit;
        public static string Sign;
        public static string RandHost;
        public static string SessionInitKey;
        public static string MasterCert;
        public static string TerminalCert;
        public static string cOutRandHost = "";
        public static int iKeyState;
        private bool? commState;

        public bool? CommState
        {
            get
            {
                if (commState == null)
                {
                    commState = true;
                }
                return commState;
            }
            set { commState = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<string> idList;

        public ObservableCollection<string> IdList
        {
            get
            {
                if (idList == null)
                {
                    List<string> l = new List<string>();
                    l.Add("所有");
                    l.AddRange(classIdService.Select());
                    idList = new ObservableCollection<string>(l);
                    
                }
                return idList;
            }
            set { idList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<string> dataChoiceList;

        public ObservableCollection<string> DataChoiceList
        {
            get
            {
                if (dataChoiceList == null)
                {
                    dataChoiceList = new ObservableCollection<string>();
                }
                return dataChoiceList;
            }
            set { dataChoiceList = value; RaisePropertyChanged(); }
        }
        private ObservableCollection<ObjectID> objectIdList;

        public ObservableCollection<ObjectID> ObjectIdList
        {
            get { return objectIdList; }
            set { objectIdList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<NormalSetData> setDataList;

        public ObservableCollection<NormalSetData> SetDataList
        {
            get { return setDataList; }
            set { setDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<ConfigTableData> configTableDataList;

        public ObservableCollection<ConfigTableData> ConfigTableDataList
        {
            get { return configTableDataList; }
            set { configTableDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<PulseData> pulseDataList;

        public ObservableCollection<PulseData> PulseDataList
        {
            get { return pulseDataList; }
            set { pulseDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<AssociationData> associationDataList;

        public ObservableCollection<AssociationData> AssociationDataList
        {
            get { return associationDataList; }
            set { associationDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<HolidayData> holidayDataList;
        public ObservableCollection<HolidayData> HolidayDataList
        {
            get { return holidayDataList; }
            set { holidayDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<CommChangeData> commChangeDataList;
        public ObservableCollection<CommChangeData> CommChangeDataList
        {
            get { return commChangeDataList; }
            set { commChangeDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<ConfigParamData> configParamDataList;
        public ObservableCollection<ConfigParamData> ConfigParamDataList
        {
            get { return configParamDataList; }
            set { configParamDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<GroupAddressData> groupAddressDataList;
        public ObservableCollection<GroupAddressData> GroupAddressDataList
        {
            get { return groupAddressDataList; }
            set { groupAddressDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<TimeZoneTableData> timeZoneTableDataList;
        public ObservableCollection<TimeZoneTableData> TimeZoneTableDataList
        {
            get { return timeZoneTableDataList; }
            set { timeZoneTableDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<PriceData> priceDataList;
        public ObservableCollection<PriceData> PriceDataList
        {
            get { return priceDataList; }
            set { priceDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<SettlementDayData> settlementDayDataList;
        public ObservableCollection<SettlementDayData> SettlementDayDataList
        {
            get { return settlementDayDataList; }
            set { settlementDayDataList = value; RaisePropertyChanged(); }
        }
        private ObservableCollection<FreezeAssociationData> freezeAssociationDataList;
        public ObservableCollection<FreezeAssociationData> FreezeAssociationDataList
        {
            get { return freezeAssociationDataList; }
            set { freezeAssociationDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<RCSDDataModel> cycleShowCSDDataList;
        public ObservableCollection<RCSDDataModel> CycleShowCSDDataList
        {
            get { return cycleShowCSDDataList; }
            set { cycleShowCSDDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<RCSDDataModel> safeModeDataList; 
        public ObservableCollection<RCSDDataModel> SafeModeDataList
        {
            get { return safeModeDataList; }
            set { safeModeDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<RCSDDataModel> timePowerDataList;
        public ObservableCollection<RCSDDataModel> TimePowerDataList
        {
            get { return timePowerDataList; }
            set { timePowerDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<DayRateData> dayRateDataList;
        public ObservableCollection<DayRateData> DayRateDataList
        {
            get { return dayRateDataList; }
            set { dayRateDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<SingleData> agreementDataList;
        public ObservableCollection<SingleData> AgreementDataList
        {
            get { return agreementDataList; }
            set { agreementDataList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<SingleData> funsPostDataList;
        public ObservableCollection<SingleData> FunsPostDataList
        {
            get { return funsPostDataList; }
            set { funsPostDataList = value; RaisePropertyChanged(); }
        }

        private int? listBoxType; 

        public int? ListBoxType
        {
            get
            {
                /*if (string.IsNullOrEmpty(listBoxType))
                {
                    listBoxType = "读取请求";
                    GetComboBoxDataChoiceData();
                }*/
                if (listBoxType == null)
                {
                    listBoxType = 0;
                    GetComboBoxDataChoiceData();
                    UpdateDataGird();
                }

                return listBoxType;
            }
            set { listBoxType = value; RaisePropertyChanged(); GetComboBoxDataChoiceData(); UpdateDataGird(); }
        }

        private int selectedType;

        public int SelectedType
        {
            get { return selectedType; }
            set { selectedType = value; RaisePropertyChanged(); }
        }
        private string selectedTypeName;

        public string SelectedTypeName
        {
            get
            {
                if (string.IsNullOrEmpty(selectedTypeName))
                {
                    SelectedType = 0;
                }
                return selectedTypeName;
            }
            set { selectedTypeName = value; RaisePropertyChanged(); GetRequstMode(); }
        }

        private int selectedClassId;

        public int SelectedClassId
        {
            get { return selectedClassId; }
            set { selectedClassId = value; RaisePropertyChanged(); UpdateDataGird(); }
        }
        /// <summary>
        /// OI数据表选择
        /// </summary>
        private int? selectedObject;

        public int? SelectedObject
        {
            get
            {
                if (selectedObject == null)
                {
                    selectedObject = 0;
                }
                return selectedObject;
            }
            set { selectedObject = value; RaisePropertyChanged(); OIDataGridSelected(); }
        }

        private int selectedLOPosition;

        public int SelectedLOPosition
        {
            get { return selectedLOPosition; }
            set { selectedLOPosition = value; RaisePropertyChanged(); SavePosition(); }
        }
        private int selectedLAPosition;

        public int SelectedLAPosition
        {
            get { return selectedLAPosition; }
            set { selectedLAPosition = value; RaisePropertyChanged(); SavePosition(); }
        }

        private string lODegree;

        public string LODegree
        {
            get { if (string.IsNullOrEmpty(lODegree)) LODegree = "0"; return lODegree; }
            set { lODegree = value; RaisePropertyChanged(); SavePosition(); }
        }
        private string lADegree;

        public string LADegree
        {
            get { if (string.IsNullOrEmpty(lADegree)) LADegree = "0"; return lADegree; }
            set { lADegree = value; RaisePropertyChanged(); SavePosition(); }
        }

        private string lOMin;

        public string LOMin
        {
            get { if (string.IsNullOrEmpty(lOMin)) LOMin = "0"; return lOMin; }
            set { lOMin = value; RaisePropertyChanged(); SavePosition(); }
        }

        private string lAMin;

        public string LAMin
        {
            get { if (string.IsNullOrEmpty(lAMin)) LAMin = "0"; return lAMin; }
            set { lAMin = value; RaisePropertyChanged(); SavePosition(); }
        }

        private string lOSec;

        public string LOSec
        {
            get { if (string.IsNullOrEmpty(lOSec)) LOSec = "0"; return lOSec; }
            set { lOSec = value; RaisePropertyChanged(); SavePosition(); }
        }

        private string lASec;

        public string LASec
        {
            get { if (string.IsNullOrEmpty(lASec)) LASec = "0"; return lASec; }
            set { lASec = value; RaisePropertyChanged(); SavePosition(); }
        }

        private string high;

        public string High
        {
            get { if (string.IsNullOrEmpty(high)) High = "0"; return high; }
            set { high = value; RaisePropertyChanged(); SavePosition(); }
        }

        private bool dataGridNormalVisibility;

        public bool DataGridNormalVisibility
        {
            get
            {

                return dataGridNormalVisibility;
            }
            set { dataGridNormalVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridConfigTableVisibility;

        public bool DataGridConfigTableVisibility
        {
            get
            {

                return dataGridConfigTableVisibility;
            }
            set { dataGridConfigTableVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridAssociationVisibility;

        public bool DataGridAssociationVisibility
        {
            get { return dataGridAssociationVisibility; }
            set { dataGridAssociationVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridPulseVisibility;

        public bool DataGridPulseVisibility
        {
            get { return dataGridPulseVisibility; }
            set { dataGridPulseVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridPositionVisibility;

        public bool DataGridPositionVisibility
        {
            get { return dataGridPositionVisibility; }
            set { dataGridPositionVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridHolidayVisibility;

        public bool DataGridHolidayVisibility
        {
            get { return dataGridHolidayVisibility; }
            set { dataGridHolidayVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridConfigParamVisibility;

        public bool DataGridConfigParamVisibility
        {
            get { return dataGridConfigParamVisibility; }
            set { dataGridConfigParamVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridGroupAddressVisibility;

        public bool DataGridGroupAddressVisibility
        {
            get { return dataGridGroupAddressVisibility; }
            set { dataGridGroupAddressVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridTimeZoneTableVisibility;

        public bool DataGridTimeZoneTableVisibility
        {
            get { return dataGridTimeZoneTableVisibility; }
            set { dataGridTimeZoneTableVisibility = value; RaisePropertyChanged(); }
        }
        private bool dataGridPriceVisibility;

        public bool DataGridPriceVisibility
        {
            get { return dataGridPriceVisibility; }
            set { dataGridPriceVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridSettlementDayVisibility;

        public bool DataGridSettlementDayVisibility
        {
            get { return dataGridSettlementDayVisibility; }
            set { dataGridSettlementDayVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridFreezeAssociationVisibility;

        public bool DataGridFreezeAssociationVisibility
        {
            get { return dataGridFreezeAssociationVisibility; }
            set { dataGridFreezeAssociationVisibility = value; RaisePropertyChanged(); }
        }

        private bool connectVisibility;

        public bool ConnectVisibility
        {
            get { return connectVisibility; }
            set { connectVisibility = value; RaisePropertyChanged(); }
        }
        private bool addBatchCollectArVisibility;

        public bool AddBatchCollectArVisibility
        {
            get { return addBatchCollectArVisibility; }
            set { addBatchCollectArVisibility = value; RaisePropertyChanged(); }
        }

        private bool addOrUpdateJobVisibility;

        public bool AddOrUpdateJobVisibility
        {
            get { return addOrUpdateJobVisibility; }
            set { addOrUpdateJobVisibility = value; RaisePropertyChanged(); }
        }

        private bool addOrUpdateConnectPlanVisibility;
        public bool AddOrUpdateConnectPlanVisibility
        {
            get { return addOrUpdateConnectPlanVisibility; }
            set { addOrUpdateConnectPlanVisibility = value; RaisePropertyChanged(); }
        }

        private bool addOrUpdateEventVisibility;
        public bool AddOrUpdateEventVisibility
        {
            get { return addOrUpdateEventVisibility; }
            set { addOrUpdateEventVisibility = value; RaisePropertyChanged(); }
        }

        private bool addOrUpdateTransPlanVisibility;
        public bool AddOrUpdateTransPlanVisibility
        {
            get { return addOrUpdateTransPlanVisibility; }
            set { addOrUpdateTransPlanVisibility = value; RaisePropertyChanged(); }
        }

        private bool btnReadVisibility;
        public bool BtnReadVisibility
        {
            get { return btnReadVisibility; }
            set { btnReadVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridCycleShowCSDVisibility;
        public bool DataGridCycleShowCSDVisibility
        {
            get { return dataGridCycleShowCSDVisibility; }
            set { dataGridCycleShowCSDVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridSafeModeVisibility;
        public bool DataGridSafeModeVisibility
        {
            get { return dataGridSafeModeVisibility; }
            set { dataGridSafeModeVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridTimePowerVisibility;
        public bool DataGridTimePowerVisibility
        {
            get { return dataGridTimePowerVisibility; }
            set { dataGridTimePowerVisibility = value; RaisePropertyChanged(); }
        }

        private bool portConfigVisibility;
        public bool PortConfigVisibility
        {
            get { return portConfigVisibility; }
            set { portConfigVisibility = value; RaisePropertyChanged(); }
        }

        private bool stepPriceVisibility;
        public bool StepPriceVisibility
        {
            get { return stepPriceVisibility; }
            set { stepPriceVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridDayRateVisibility;
        public bool DataGridDayRateVisibility
        {
            get { return dataGridDayRateVisibility; }
            set { dataGridDayRateVisibility = value; RaisePropertyChanged(); }
        }

        private bool dayRateTotalVisibility;
        public bool DayRateTotalVisibility
        {
            get { return dayRateTotalVisibility; }
            set { dayRateTotalVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridAgreementVisibility;
        public bool DataGridAgreementVisibility
        {
            get { return dataGridAgreementVisibility; }
            set { dataGridAgreementVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridFunsPostVisibility; 
        public bool DataGridFunsPostVisibility
        {
            get { return dataGridFunsPostVisibility; }
            set { dataGridFunsPostVisibility = value; RaisePropertyChanged(); }
        }

        private bool dataGridCommChangeVisibility; 
        public bool DataGridCommChangeVisibility
        {
            get { return dataGridCommChangeVisibility; }
            set { dataGridCommChangeVisibility = value; RaisePropertyChanged(); }
        }

        private bool addOrUpdateReportVisibility; 
        public bool AddOrUpdateReportVisibility
        {
            get { return addOrUpdateReportVisibility; }
            set { addOrUpdateReportVisibility = value; RaisePropertyChanged(); }
        }

        public IEventAction[] DataGridActionsCommand { get; set; }
        /// <summary>
        /// ctor
        /// </summary>
        public AppControlViewModel()
        {
            this.DataGridActionsCommand = new IEventAction[]
            {
                new EventAction<object,DataGridCellEditEndingEventArgs>("CellEditEnding",DataGridCellEditEndingChanged),
                new EventAction<object,KeyEventArgs>("PreviewKeyDown",KeyDown),
                

            };

        }

        private void KeyDown(object arg1, KeyEventArgs args)
        {
            if (args.Key == Key.Delete)
            {
                // 在这里编写处理删除键的代码
                if (arg1 is DataGrid dataGrid)
                {
                    var index = dataGrid.SelectedIndex;
                    gWCmdMakeUpSelected = gWCmdMakeUps[0];
                    switch (dataGrid.Name)
                    {
                        case "dataGridConfigTable":
                            ConfigTableDataList.RemoveAt(index);
                            SaveConfigTableDataGrid();
                            break;
                        case "dataGridPulse":
                            PulseDataList.RemoveAt(index);
                            SavePulseDataGrid();
                            break;
                        case "dataGridAssociation":
                            AssociationDataList.RemoveAt(index);
                            SaveAssociationDataGrid();
                            break;
                        case "dataGridAgreement":
                            AgreementDataList.RemoveAt(index);
                            SaveSingleDataGrid(agreementDataList);
                            break;
                        case "dataGridFunsPost":
                            FunsPostDataList.RemoveAt(index);
                            SaveSingleDataGrid(funsPostDataList);
                            break;
                        case "dataGridHoliday":
                            
                            HolidayDataList.RemoveAt(index);
                            SaveHolidayDataGrid();
                            break;
                        case "dataGridGroupAddress":

                            GroupAddressDataList.RemoveAt(index);
                            SaveGroupAddressDataGrid();
                            break;
                        case "dataGridTimeZoneTable":
                            TimeZoneTableDataList.RemoveAt(index);
                            SaveTimeZoneTableDataGrid();
                            break;
                        case "dataGridPrice":
                            PriceDataList.RemoveAt(index);
                            SavePriceDataGrid();
                            break;
                        case "dataGridSettlementDay":
                            SettlementDayDataList.RemoveAt(index);
                            SaveSettlementDayDataGrid();
                            break;
                        case "dataGridFreezeAssociation":
                            FreezeAssociationDataList.RemoveAt(index);
                            SaveFreezeAssociationDataGrid();
                            break;
                        case "dataGridCycleShowCSD":
                            CycleShowCSDDataList.RemoveAt(index);
                            SaveRCSDDataModel(CycleShowCSDDataList);

                            break;
                        case "dataGridSafeMode":
                            SafeModeDataList.RemoveAt(index);
                            SaveRCSDDataModel(SafeModeDataList);
                            break;
                        case "dataGridTimePower":
                            TimePowerDataList.RemoveAt(index);
                            SaveRCSDDataModel(TimePowerDataList);
                            break;
                        case "dataGridDayRate":
                            DayRateDataList.RemoveAt(index);
                            SaveDayRateData();
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        private void DataGridCellEditEndingChanged(object arg1, DataGridCellEditEndingEventArgs args)
        {
            if (args.EditAction == DataGridEditAction.Commit)
            {
                if (arg1 is DataGrid dataGrid)
                {
                    var el = args.EditingElement as TextBox;
                    switch (dataGrid.Name)
                    {
                        case "dataGridNormal":
                            if (dataGrid.SelectedIndex >= gWCmdMakeUps.Count)
                            {
                                break;
                            }
                            gWCmdMakeUpSelected = gWCmdMakeUps[dataGrid.SelectedIndex];
                            gWCmdMakeUpSelected.DataValue = el.Text;
                            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
                            break;
                        case "dataGridConfigTable":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            var column = args.Column as DataGridBoundColumn;
                            ConfigTableData c = configTableDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        c.TSA = el.Text;
                                        break;
                                    case 1:
                                        c.TotalFlag = el.Text;
                                        break;
                                    case 2:
                                        c.OperFlag = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveConfigTableDataGrid();
                            }
                            break;
                        case "dataGridPulse":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            PulseData p = pulseDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        p.OAD = el.Text;
                                        break;
                                    case 1:
                                        p.Enum = el.Text;
                                        break;
                                    case 2:
                                        p.K = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SavePulseDataGrid();
                            }
                            break;
                        case "dataGridAssociation":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            if (column != null)
                            {
                                associationDataList[dataGrid.SelectedIndex].OAD = el.Text;
                                SaveAssociationDataGrid();
                            }
                            break;
                        case "dataGridAgreement":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            if (column != null)
                            {
                                if (string.IsNullOrWhiteSpace(el.Text))
                                {
                                    agreementDataList.RemoveAt(dataGrid.SelectedIndex);
                                }
                                else
                                {
                                    agreementDataList[dataGrid.SelectedIndex].Name = el.Text;
                                }
                                
                                SaveSingleDataGrid(agreementDataList);
                            }
                            break;
                        case "dataGridFunsPost":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            if (column != null)
                            {
                                funsPostDataList[dataGrid.SelectedIndex].Name = el.Text;
                                SaveSingleDataGrid(funsPostDataList);
                            }
                            break;
                        case "dataGridHoliday":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            HolidayData h = holidayDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        h.DateTime = el.Text;
                                        break;
                                    case 1:
                                        h.Address = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveHolidayDataGrid();
                            }
                            break;
                        case "dataGridGroupAddress":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            if (column != null)
                            {
                                groupAddressDataList[dataGrid.SelectedIndex].Address = el.Text;
                                SaveGroupAddressDataGrid();
                            }
                            break;
                        case "dataGridTimeZoneTable":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            TimeZoneTableData t = timeZoneTableDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        t.Month = el.Text;
                                        break;
                                    case 1:
                                        t.Day = el.Text;
                                        break;
                                    case 2:
                                        t.Address = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveTimeZoneTableDataGrid();
                            }
                            break;
                        case "dataGridPrice":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            if (column != null)
                            {
                                priceDataList[dataGrid.SelectedIndex].Price = el.Text;
                                SavePriceDataGrid();
                            }
                            break;
                        case "dataGridSettlementDay":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            SettlementDayData s = settlementDayDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        s.Day = el.Text;
                                        break;
                                    case 1:
                                        s.Hour = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveSettlementDayDataGrid();
                            }
                            break;
                        case "dataGridFreezeAssociation":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            FreezeAssociationData f = freezeAssociationDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        f.Cycle = el.Text;
                                        break;
                                    case 1:
                                        f.OAD = el.Text;
                                        break;
                                    case 2:
                                        f.Deep = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveFreezeAssociationDataGrid();
                            }
                            break;
                        case "dataGridCycleShowCSD":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            RCSDDataModel rCSDDataModel = CycleShowCSDDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        rCSDDataModel.CSD = el.Text;
                                        break;
                                    case 1:
                                        rCSDDataModel.Data = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveRCSDDataModel(CycleShowCSDDataList);
                            }
                            break;
                        case "dataGridSafeMode":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            rCSDDataModel = SafeModeDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        rCSDDataModel.CSD = el.Text;
                                        break;
                                    case 1:
                                        rCSDDataModel.Data = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveRCSDDataModel(SafeModeDataList);
                            }
                            break;
                        case "dataGridTimePower":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            rCSDDataModel = TimePowerDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        rCSDDataModel.CSD = el.Text;
                                        break;
                                    case 1:
                                        rCSDDataModel.Data = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveRCSDDataModel(TimePowerDataList);
                            }
                            break;
                        case "dataGridDayRate":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            DayRateData dayRateData = DayRateDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        dayRateData.Hour = el.Text;
                                        break;
                                    case 1:
                                        dayRateData.Min = el.Text;
                                        break;
                                    case 2:
                                        dayRateData.Rate = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveDayRateData();
                            }
                            break;
                        case "dataGridCommChange":
                            gWCmdMakeUpSelected = gWCmdMakeUps[0];
                            column = args.Column as DataGridBoundColumn;
                            CommChangeData commChangeData = CommChangeDataList[dataGrid.SelectedIndex];
                            if (column != null)
                            {
                                switch (column.DisplayIndex)
                                {
                                    case 0:
                                        commChangeData.Address = el.Text;
                                        break;
                                    case 1:
                                        commChangeData.Port = el.Text;
                                        break;
                                    default:
                                        break;
                                }
                                SaveCommChangeData();
                            }
                            break;
                        default:
                            break;
                    }

                }
            }

        }


        #endregion

        #region 方法
        private void SaveConfigTableDataGrid()
        {
            string value = "";
            string temp;
            ConfigTableData c;
            for (int i = 0; i < configTableDataList.Count; i++)
            {
                c = configTableDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(c.TSA))
                {
                    return;
                }
                else
                {
                    temp += c.TSA;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(c.TotalFlag))
                {
                    return;
                }
                else
                {
                    temp += c.TotalFlag;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(c.OperFlag))
                {
                    return;
                }
                else
                {
                    temp += c.OperFlag;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SavePulseDataGrid()
        {
            string value = "";
            string temp;
            PulseData c;
            for (int i = 0; i < pulseDataList.Count; i++)
            {
                c = pulseDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(c.OAD))
                {
                    value = value.Trim(';');
                    gWCmdMakeUpSelected.DataValue = value;
                    gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
                    return;
                }
                else
                {
                    temp += c.OAD;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(c.Enum))
                {
                    value = value.Trim(';');
                    gWCmdMakeUpSelected.DataValue = value;
                    gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
                    return;
                }
                else
                {
                    temp += c.Enum;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(c.K))
                {
                    value = value.Trim(';');
                    gWCmdMakeUpSelected.DataValue = value;
                    gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
                    return;
                }
                else
                {
                    temp += c.K;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveAssociationDataGrid()
        {
            string value = "";
            string temp;
            AssociationData a;
            for (int i = 0; i < associationDataList.Count; i++)
            {
                a = associationDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(a.OAD))
                {
                    return;
                }
                else
                {
                    temp += a.OAD;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveSingleDataGrid(ObservableCollection<SingleData> list)
        {
            string value = "";
            string temp;
            SingleData a;
            for (int i = 0; i < list.Count; i++)
            {
                a = list[i];
                temp = "";
                if (string.IsNullOrEmpty(a.Name))
                {
                    return;
                }
                else
                {
                    temp += a.Name;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SavePosition()
        {
            if (gWCmdMakeUpSelected == null)
            {
                return;
            }
            string value = "";
            value += SelectedLOPosition.ToString();
            value += ";";
            value += LODegree;
            value += ";";
            value += LOMin;
            value += ";";
            value += LOSec;
            value += ";";
            value += SelectedLAPosition.ToString();
            value += ";";
            value += LADegree;
            value += ";";
            value += LAMin;
            value += ";";
            value += LASec;
            value += ";";
            value += High;
            value += ";";
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveHolidayDataGrid()
        {
            string value = "";
            string temp;
            HolidayData h;
            for (int i = 0; i < pulseDataList.Count; i++)
            {
                h = holidayDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(h.DateTime))
                {
                    return;
                }
                else
                {
                    temp += h.DateTime;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(h.Address))
                {
                    return;
                }
                else
                {
                    temp += h.Address;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveGroupAddressDataGrid()
        {
            string value = "";
            string temp;
            GroupAddressData a;
            for (int i = 0; i < groupAddressDataList.Count; i++)
            {
                a = groupAddressDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(a.Address))
                {
                    return;
                }
                else
                {
                    temp += a.Address;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveTimeZoneTableDataGrid()
        {
            string value = "";
            string temp;
            TimeZoneTableData t;
            for (int i = 0; i < TimeZoneTableDataList.Count; i++)
            {
                t = timeZoneTableDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(t.Month))
                {
                    return;
                }
                else
                {
                    temp += t.Month;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(t.Day))
                {
                    return;
                }
                else
                {
                    temp += t.Day;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(t.Address))
                {
                    return;
                }
                else
                {
                    temp += t.Address;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SavePriceDataGrid()
        {
            string value = "";
            string temp;
            PriceData p;
            for (int i = 0; i < priceDataList.Count; i++)
            {
                p = priceDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(p.Price))
                {
                    return;
                }
                else
                {
                    temp += p.Price;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveSettlementDayDataGrid()
        {
            string value = "";
            string temp;
            SettlementDayData s;
            for (int i = 0; i < pulseDataList.Count; i++)
            {
                s = settlementDayDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(s.Day))
                {
                    return;
                }
                else
                {
                    temp += s.Day;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(s.Hour))
                {
                    return;
                }
                else
                {
                    temp += s.Hour;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveFreezeAssociationDataGrid()
        {
            string value = "";
            string temp;
            FreezeAssociationData f;
            for (int i = 0; i < pulseDataList.Count; i++)
            {
                f = freezeAssociationDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(f.Cycle))
                {
                    return;
                }
                else
                {
                    temp += f.Cycle;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(f.OAD))
                {
                    return;
                }
                else
                {
                    temp += f.OAD;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(f.Deep))
                {
                    return;
                }
                else
                {
                    temp += f.Deep;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveRCSDDataModel(ObservableCollection<RCSDDataModel> list)
        {
            string value = "";
            string temp;
            RCSDDataModel rCSDDataModel;
            for (int i = 0; i < list.Count; i++)
            {
                rCSDDataModel = list[i];
                temp = "";
                if (string.IsNullOrEmpty(rCSDDataModel.CSD))
                {
                    return;
                }
                else
                {
                    temp += rCSDDataModel.CSD;
                    temp += ";";
                }

                if (string.IsNullOrEmpty(rCSDDataModel.Data))
                {
                    return;
                }
                else
                {
                    temp += rCSDDataModel.Data;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        private void SaveDayRateData()
        {
            string value = "";
            string temp;
            DayRateData s;
            for (int i = 0; i < DayRateDataList.Count; i++)
            {
                s = DayRateDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(s.Hour))
                {
                    return;
                }
                else
                {
                    temp += s.Hour;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(s.Min))
                {
                    return;
                }
                else
                {
                    temp += s.Min;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(s.Rate))
                {
                    return;
                }
                else
                {
                    temp += s.Rate;
                    temp += ";";
                }
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }

        private void SaveCommChangeData()
        {
            string value = "";
            string temp;
            CommChangeData s;
            for (int i = 0; i < CommChangeDataList.Count; i++)
            {
                s = CommChangeDataList[i];
                temp = "";
                if (string.IsNullOrEmpty(s.Address))
                {
                    return;
                }
                else
                {
                    temp += s.Address;
                    temp += ";";
                }
                if (string.IsNullOrEmpty(s.Port))
                {
                    return;
                }
                else
                {
                    temp += s.Port;
                    temp += ";";
                }
                
                value += temp;
            }
            value = value.Trim(';');
            gWCmdMakeUpSelected.DataValue = value;
            gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
        }
        /// <summary>
        /// 切换设置参数表格
        /// </summary>
        /// <param name="zIndexName"></param>
        private void SetZIndex(string zIndexName)
        {
            DataGridNormalVisibility = false;
            DataGridConfigTableVisibility = false;
            DataGridPulseVisibility = false;
            DataGridAssociationVisibility = false;
            DataGridPositionVisibility = false;
            DataGridHolidayVisibility = false;
            DataGridConfigParamVisibility = false;
            DataGridGroupAddressVisibility = false;
            DataGridTimeZoneTableVisibility = false;
            DataGridPriceVisibility = false;
            DataGridSettlementDayVisibility = false;
            DataGridFreezeAssociationVisibility = false;
            ConnectVisibility = false;
            AddBatchCollectArVisibility = false;
            AddOrUpdateJobVisibility = false;
            AddOrUpdateConnectPlanVisibility = false;
            AddOrUpdateEventVisibility = false;
            AddOrUpdateTransPlanVisibility = false;
            DataGridCycleShowCSDVisibility = false;
            DataGridSafeModeVisibility = false;
            DataGridTimePowerVisibility = false;
            PortConfigVisibility = false;
            StepPriceVisibility = false;
            DataGridDayRateVisibility = false;
            DayRateTotalVisibility = false;
            DataGridAgreementVisibility = false;
            DataGridFunsPostVisibility = false;
            DataGridCommChangeVisibility = false;
            AddOrUpdateReportVisibility = false;
            Messenger.Default.Send<bool>(false, "ConnectVisibility");
            switch (zIndexName)
            {
                case "DataGridNormalVisibility":
                    DataGridNormalVisibility = true;
                    break;
                case "DataGridConfigTableVisibility":
                    DataGridConfigTableVisibility = true;
                    break;
                case "DataGridPulseVisibility":
                    DataGridPulseVisibility = true;
                    break;
                case "DataGridAssociationVisibility":
                    DataGridAssociationVisibility = true;
                    break;
                case "DataGridPositionVisibility":
                    DataGridPositionVisibility = true;
                    break;
                case "DataGridHolidayVisibility":
                    DataGridHolidayVisibility = true;
                    break;
                case "DataGridConfigParamVisibility":
                    DataGridConfigParamVisibility = true;
                    break;
                case "DataGridGroupAddressVisibility":
                    DataGridGroupAddressVisibility = true;
                    break;
                case "DataGridTimeZoneTableVisibility":
                    DataGridTimeZoneTableVisibility = true;
                    break;
                case "DataGridPriceVisibility":
                    DataGridPriceVisibility = true;
                    break;
                case "DataGridSettlementDayVisibility":
                    DataGridSettlementDayVisibility = true;
                    break;
                case "DataGridFreezeAssociationVisibility":
                    DataGridFreezeAssociationVisibility = true;
                    break;
                case "ConnectVisibility":
                    ConnectVisibility = true;
                    //Messenger.Default.Send<bool>(true, "ConnectVisibility");
                    //CONNECTControlViewModel.action(true);
                    break;
                case "AddBatchCollectArVisibility":
                    AddBatchCollectArVisibility = true;
                    break;
                case "AddOrUpdateJobVisibility":
                    AddOrUpdateJobVisibility = true;
                    break;
                case "AddOrUpdateConnectPlanVisibility":
                    AddOrUpdateConnectPlanVisibility = true;
                    break;
                case "AddOrUpdateEventVisibility":
                    AddOrUpdateEventVisibility = true;
                    break;
                case "AddOrUpdateTransPlanVisibility":
                    AddOrUpdateTransPlanVisibility = true;
                    break;
                case "DataGridCycleShowCSDVisibility":
                    DataGridCycleShowCSDVisibility = true;
                    break;
                case "DataGridSafeModeVisibility":
                    DataGridSafeModeVisibility = true;
                    break;
                case "DataGridTimePowerVisibility":
                    DataGridTimePowerVisibility = true;
                    break;
                case "PortConfigVisibility":
                    PortConfigVisibility = true;
                    break;
                case "StepPriceVisibility":
                    StepPriceVisibility = true;
                    break;
                case "DataGridDayRateVisibility":
                    DataGridDayRateVisibility = true;
                    break;
                case "DayRateTotalVisibility":
                    DayRateTotalVisibility = true;
                    break;
                case "DataGridAgreementVisibility":
                    DataGridAgreementVisibility = true;
                    break;
                case "DataGridFunsPostVisibility":
                    DataGridFunsPostVisibility = true;
                    break;
                case "DataGridCommChangeVisibility":
                    DataGridCommChangeVisibility = true;
                    break;
                case "AddOrUpdateReportVisibility":
                    AddOrUpdateReportVisibility = true;
                    break;
                default:
                    break;
            }

        }
        
        /// <summary>
        /// 生成设置参数列表
        /// </summary>
        private void OIDataGridSelected()
        {
            if (SelectedObject < 0)
            {
                SelectedObject = 0;
            }
            if (ObjectIdList == null || ObjectIdList.Count <= 0)
            {
                return;
            }
            Console.WriteLine("=======================");
            var o = ObjectIdList[(int)SelectedObject];
            var list = getGWCmdMakeUpList(o);
            string OADName = o.ObjectDes;
            if (list?.Count > 0)
            {
                if (OADName.Contains("总加配置表") || OADName.Contains("批量添加"))
                {

                    List<ConfigTableData> configTableList = new List<ConfigTableData>();
                    if (ConfigTableDataList != null)
                    {
                        ConfigTableDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 3)
                            {
                                ConfigTableData configTableData = new ConfigTableData();
                                configTableData.TSA = strings[i];
                                configTableData.TotalFlag = strings[i + 1];
                                configTableData.OperFlag = strings[i + 2];
                                configTableList.Add(configTableData);
                            }
                            ConfigTableDataList = new ObservableCollection<ConfigTableData>(configTableList);
                        }
                        else
                        {
                            ConfigTableDataList = new ObservableCollection<ConfigTableData>();
                        }
                    }

                    SetZIndex("DataGridConfigTableVisibility");
                }
                else if (OADName.Contains("脉冲配置"))
                {
                    List<PulseData> pulseList = new List<PulseData>();
                    if (PulseDataList != null)
                    {
                        PulseDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 3)
                            {
                                PulseData configTableData = new PulseData();
                                configTableData.OAD = strings[i];
                                configTableData.Enum = strings[i + 1];
                                configTableData.K = strings[i + 2];
                                pulseList.Add(configTableData);
                            }
                            PulseDataList = new ObservableCollection<PulseData>(pulseList);
                        }
                        else
                        {
                            PulseDataList = new ObservableCollection<PulseData>();
                        }
                    }

                    SetZIndex("DataGridPulseVisibility");
                }
                else if (OADName.Contains("事件-关联对象属性表") || OADName.Contains("恢复出厂参数") || OADName.Contains("上报通道"))
                {
                    List<AssociationData> associationList = new List<AssociationData>();
                    if (AssociationDataList != null)
                    {
                        AssociationDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i++)
                            {
                                AssociationData associationData = new AssociationData();
                                associationData.OAD = strings[i];
                                associationList.Add(associationData);
                            }
                            AssociationDataList = new ObservableCollection<AssociationData>(associationList);
                        }
                        else
                        {
                            AssociationDataList = new ObservableCollection<AssociationData>();
                        }
                    }

                    SetZIndex("DataGridAssociationVisibility");
                }
                else if (OADName.Contains("规约列表"))
                {
                    List<SingleData> agreementList = new List<SingleData>();
                    if (AgreementDataList != null)
                    {
                        AgreementDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i++)
                            {
                                SingleData singleData = new SingleData();
                                singleData.Name = strings[i];
                                agreementList.Add(singleData);
                            }
                            AgreementDataList = new ObservableCollection<SingleData>(agreementList);
                        }
                        else
                        {
                            AgreementDataList = new ObservableCollection<SingleData>();
                        }
                    }

                    SetZIndex("DataGridAgreementVisibility");
                }
                else if (OADName.Equals("多功能端子"))
                {
                    List<SingleData> funsPostList = new List<SingleData>();
                    if (FunsPostDataList != null)
                    {
                        FunsPostDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i++)
                            {
                                SingleData singleData = new SingleData();
                                singleData.Name = strings[i];
                                funsPostList.Add(singleData);
                            }
                            FunsPostDataList = new ObservableCollection<SingleData>(funsPostList);
                        }
                        else
                        {
                            FunsPostDataList = new ObservableCollection<SingleData>();
                        }
                    }

                    SetZIndex("DataGridAgreementVisibility");
                }
                else if (OADName.Contains("地理位置"))
                {
                    gWCmdMakeUpSelected = list[0];
                    if (gWCmdMakeUpSelected != null)
                    {
                        var strings = gWCmdMakeUpSelected.DataValue.Split(';');
                        SelectedLOPosition = int.Parse(strings[0]);
                        LODegree = strings[1];
                        LOMin = strings[2];
                        LOSec = strings[3];
                        SelectedLAPosition = int.Parse(strings[4]);
                        LADegree = strings[5];
                        LAMin = strings[6];
                        LASec = strings[7];
                        High = strings[8];
                    }


                    SetZIndex("DataGridPositionVisibility");
                }
                else if (OADName.Contains("公共假日表"))
                {
                    List<HolidayData> holidayList = new List<HolidayData>();
                    if (HolidayDataList != null)
                    {
                        HolidayDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 2)
                            {
                                HolidayData holidayData = new HolidayData();
                                holidayData.DateTime = strings[i];
                                holidayData.Address = strings[i + 1];
                                holidayList.Add(holidayData);
                            }
                            HolidayDataList = new ObservableCollection<HolidayData>(holidayList);
                        }
                        else
                        {
                            HolidayDataList = new ObservableCollection<HolidayData>();
                        }
                    }
                    SetZIndex("DataGridHolidayVisibility");
                }
                else if (OADName.Equals("协议通道切换")|| OADName.Equals("主站通信参数表")|| OADName.Contains("以太网通信模块-主站通讯参数表"))
                {
                    List<CommChangeData> commChangeList = new List<CommChangeData>();
                    if (CommChangeDataList != null)
                    {
                        CommChangeDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 2)
                            {
                                CommChangeData commChangeData = new CommChangeData();
                                commChangeData.Address = strings[i];
                                commChangeData.Port = strings[i + 1];
                                commChangeList.Add(commChangeData);
                            }
                            CommChangeDataList = new ObservableCollection<CommChangeData>(commChangeList);
                        }
                        else
                        {
                            CommChangeDataList = new ObservableCollection<CommChangeData>();
                        }
                    }
                    SetZIndex("DataGridCommChangeVisibility");
                }
                else if (OADName.Contains("有功总电能量差动越限事件记录-配置参数"))
                {
                    List<ConfigParamData> configParamList = new List<ConfigParamData>();
                    if (HolidayDataList != null)
                    {
                        HolidayDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 6)
                            {
                                ConfigParamData configParamData = new ConfigParamData();
                                configParamData.Id = strings[0];
                                configParamData.OIContrast = strings[1];
                                configParamData.OIRefer = strings[2];
                                configParamData.Flag = strings[3];
                                configParamData.DeviationReData = strings[4];
                                configParamData.DeviationAbData = strings[5];
                                configParamList.Add(configParamData);
                            }
                            ConfigParamDataList = new ObservableCollection<ConfigParamData>(configParamList);
                        }
                        else
                        {
                            ConfigParamDataList = new ObservableCollection<ConfigParamData>();
                        }
                    }
                    SetZIndex("DataGridConfigParamVisibility");
                }
                else if (OADName.Contains("组地址"))
                {
                    List<GroupAddressData> groupAddressList = new List<GroupAddressData>();
                    if (AssociationDataList != null)
                    {
                        AssociationDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i++)
                            {
                                GroupAddressData groupAddressData = new GroupAddressData();
                                groupAddressData.Address = strings[i];
                                groupAddressList.Add(groupAddressData);
                            }
                            GroupAddressDataList = new ObservableCollection<GroupAddressData>(groupAddressList);
                        }
                        else
                        {
                            GroupAddressDataList = new ObservableCollection<GroupAddressData>();
                        }
                    }

                    SetZIndex("DataGridGroupAddressVisibility");
                }
                else if (OADName.Contains("当前套时区表") || OADName.Contains("备用套时区表"))
                {
                    List<TimeZoneTableData> timeZoneTableList = new List<TimeZoneTableData>();
                    if (PulseDataList != null)
                    {
                        PulseDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 3)
                            {
                                TimeZoneTableData timeZoneTableData = new TimeZoneTableData();
                                timeZoneTableData.Month = strings[i];
                                timeZoneTableData.Day = strings[i + 1];
                                timeZoneTableData.Address = strings[i + 2];
                                timeZoneTableList.Add(timeZoneTableData);
                            }
                            TimeZoneTableDataList = new ObservableCollection<TimeZoneTableData>(timeZoneTableList);
                        }
                        else
                        {
                            TimeZoneTableDataList = new ObservableCollection<TimeZoneTableData>();
                        }
                    }

                    SetZIndex("DataGridTimeZoneTableVisibility");
                }
                else if (OADName.Contains("当前套日时段表1")
                    || OADName.Contains("当前套日时段表2")
                    || OADName.Contains("当前套日时段表3")
                    || OADName.Contains("当前套日时段表4")
                    || OADName.Contains("当前套日时段表5")
                    || OADName.Contains("当前套日时段表6")
                    || OADName.Contains("当前套日时段表7")
                    || OADName.Contains("当前套日时段表8")
                    || OADName.Contains("备用套日时段表1")
                    || OADName.Contains("备用套日时段表2")
                    || OADName.Contains("备用套日时段表3")
                    || OADName.Contains("备用套日时段表4")
                    || OADName.Contains("备用套日时段表5")
                    || OADName.Contains("备用套日时段表6")
                    || OADName.Contains("备用套日时段表7")
                    || OADName.Contains("备用套日时段表8"))
                {
                    List<DayRateData> dayRateTableList = new List<DayRateData>();
                    if (PulseDataList != null)
                    {
                        PulseDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 3)
                            {
                                DayRateData dayRateData = new DayRateData();
                                dayRateData.Hour = strings[i];
                                dayRateData.Min = strings[i + 1];
                                dayRateData.Rate = strings[i + 2];
                                dayRateTableList.Add(dayRateData);
                            }
                            DayRateDataList = new ObservableCollection<DayRateData>(dayRateTableList);
                        }
                        else
                        {
                            DayRateDataList = new ObservableCollection<DayRateData>();
                        }
                    }

                    SetZIndex("DataGridDayRateVisibility");
                }
                else if (OADName.Contains("套费率电价"))
                {
                    List<PriceData> priceList = new List<PriceData>();
                    if (AssociationDataList != null)
                    {
                        AssociationDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i++)
                            {
                                PriceData priceData = new PriceData();
                                priceData.Price = strings[i];
                                priceList.Add(priceData);
                            }
                            PriceDataList = new ObservableCollection<PriceData>(priceList);
                        }
                        else
                        {
                            PriceDataList = new ObservableCollection<PriceData>();
                        }
                    }

                    SetZIndex("DataGridPriceVisibility");
                }
                else if (OADName.Equals("结算日"))
                {
                    List<SettlementDayData> settlementDayList = new List<SettlementDayData>();
                    if (HolidayDataList != null)
                    {
                        HolidayDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 2)
                            {
                                SettlementDayData s = new SettlementDayData();
                                s.Day = strings[i];
                                s.Hour = strings[i + 1];
                                settlementDayList.Add(s);
                            }
                            SettlementDayDataList = new ObservableCollection<SettlementDayData>(settlementDayList);
                        }
                        else
                        {
                            SettlementDayDataList = new ObservableCollection<SettlementDayData>();
                        }
                    }
                    SetZIndex("DataGridSettlementDayVisibility");
                }
                else if (OADName.Contains("冻结-关联对象属性表"))
                {
                    List<FreezeAssociationData> freezeAssociationList = new List<FreezeAssociationData>();
                    if (FreezeAssociationDataList != null)
                    {
                        FreezeAssociationDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 3)
                            {
                                FreezeAssociationData freezeAssociationData = new FreezeAssociationData();
                                freezeAssociationData.Cycle = strings[i];
                                freezeAssociationData.OAD = strings[i + 1];
                                freezeAssociationData.Deep = strings[i + 2];
                                freezeAssociationList.Add(freezeAssociationData);
                            }
                            FreezeAssociationDataList = new ObservableCollection<FreezeAssociationData>(freezeAssociationList);
                        }
                        else
                        {
                            FreezeAssociationDataList = new ObservableCollection<FreezeAssociationData>();
                        }
                    }

                    SetZIndex("DataGridFreezeAssociationVisibility");
                }
                else if (OADName.Contains("显示对象列表"))
                {
                    List<RCSDDataModel> cycleShowCSDList = new List<RCSDDataModel>();
                    if (CycleShowCSDDataList != null)
                    {
                        CycleShowCSDDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 2)
                            {
                                RCSDDataModel rCSDDataModel = new RCSDDataModel();
                                rCSDDataModel.CSD = strings[i];
                                rCSDDataModel.Data = strings[i + 1];
                                cycleShowCSDList.Add(rCSDDataModel);
                            }
                            CycleShowCSDDataList = new ObservableCollection<RCSDDataModel>(cycleShowCSDList);
                        }
                        else
                        {
                            CycleShowCSDDataList = new ObservableCollection<RCSDDataModel>();
                        }
                    }

                    SetZIndex("DataGridCycleShowCSDVisibility");
                }
                else if (OADName.Equals("显式安全模式参数"))
                {
                    List<RCSDDataModel> safeModeList = new List<RCSDDataModel>();
                    if (SafeModeDataList != null)
                    {
                        SafeModeDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');
                            for (int i = 0; i < strings.Length; i += 2)
                            {
                                RCSDDataModel rCSDDataModel = new RCSDDataModel();
                                rCSDDataModel.CSD = strings[i];
                                rCSDDataModel.Data = strings[i + 1];
                                safeModeList.Add(rCSDDataModel);
                            }
                            SafeModeDataList = new ObservableCollection<RCSDDataModel>(safeModeList);
                        }
                        else
                        {
                            SafeModeDataList = new ObservableCollection<RCSDDataModel>();
                        }
                    }

                    SetZIndex("DataGridSafeModeVisibility");
                }
                else if (OADName.Equals("时段功控"))
                {
                    List<RCSDDataModel> timePowerList = new List<RCSDDataModel>();
                    if (TimePowerDataList != null)
                    {
                        TimePowerDataList.Clear();
                    }
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.DataValue))
                        {
                            string[] strings = item.DataValue.Split(';');

                            for (int i = 0; i < strings.Length; i += 2)
                            {
                                RCSDDataModel rCSDDataModel = new RCSDDataModel();
                                rCSDDataModel.CSD = strings[i];
                                rCSDDataModel.Data = strings[i + 1];
                                timePowerList.Add(rCSDDataModel);
                            }
                            TimePowerDataList = new ObservableCollection<RCSDDataModel>(timePowerList);
                        }
                        else
                        {
                            TimePowerDataList = new ObservableCollection<RCSDDataModel>();
                        }
                    }

                    SetZIndex("DataGridTimePowerVisibility");
                }
                else if (OADName.Contains("建立应用连接"))
                {
                    CONNECTControlViewModel.GWCmdMakeUp = list[0];
                    ServiceLocator.Current.GetInstance<CONNECTControlViewModel>().UpdateData();
                    SetZIndex("ConnectVisibility");
                }
                else if (OADName.Contains("AddBatch"))
                {

                    SetZIndex("AddBatchCollectArVisibility");
                }
                else if (OADName.Contains("RS232") || OADName.Contains("RS485") || OADName.Equals("红外"))
                {
                    PortConfigViewModel.GWCmdMakeUp = list[0];
                    ServiceLocator.Current.GetInstance<PortConfigViewModel>().UpdateData();
                    SetZIndex("PortConfigVisibility");
                }
                else if (OADName.Contains("套阶梯电价"))
                {
                    StepPriceViewModel.GWCmdMakeUp = list[0];
                    ServiceLocator.Current.GetInstance<StepPriceViewModel>().UpdateData();
                    SetZIndex("StepPriceVisibility");
                }
                else if (OADName.Equals("当前套日时段表") || OADName.Equals("备用套日时段表"))
                {
                    DayRateTotalViewModel.GWCmdMakeUp = list[0];
                    ServiceLocator.Current.GetInstance<DayRateTotalViewModel>().UpdateData();
                    SetZIndex("DayRateTotalVisibility");
                }
                else if (OADName.Contains("添加或更新一组任务配置单元"))
                {

                    SetZIndex("AddOrUpdateJobVisibility");
                }
                else if (OADName.Contains("添加或更新一组普通采集方案"))
                {

                    SetZIndex("AddOrUpdateConnectPlanVisibility");
                }
                else if (OADName.Contains("添加或更新一组事件采集方案"))
                {

                    SetZIndex("AddOrUpdateEventVisibility");
                }
                else if (OADName.Contains("添加更新一个透明方案"))
                {

                    SetZIndex("AddOrUpdateTransPlanVisibility");
                }
                else if (OADName.Contains("上报方案集-添加或更新一组上报方案"))
                {

                    SetZIndex("AddOrUpdateReportVisibility");
                }
                else if (list != null && list.Count > 0)
                {
                    int AttributeID = (int)o.AttributeID;
                    string OAD;
                    if (o._ObjectID.ToString().Length == 8)
                    {
                        OAD = o._ObjectID.ToString();
                    }
                    else
                    {
                        OAD = o._ObjectID.ToString() + AttributeID.ToString("X2") + "00";
                    }
                    var query = SqlSugarHelper.Db.Queryable<GWCmdMakeUp>()
                     .LeftJoin<CJDataType>((g, c) => g.DataFormat == c.Datatypeid)//多个条件用&&
                     .Where(g => g.ObjectIdentifier.Equals(OAD)).Where(g => g.OpenrateType.Equals(o.ClientAPDU))
                     .Select((g, c) => new NormalSetData { SubItemName = g.SubItemName, DataValue = g.DataValue, Remark = g.Remark, Typename = c.Typename, Example = c.Example })
                     .ToList();
                    SetDataList = new ObservableCollection<NormalSetData>(query);
                    SetZIndex("DataGridNormalVisibility");
                }
            }
            
            else
            {
                SetZIndex("EmptyZIndex");
            }
            gWCmdMakeUps = list;
        }
        /// <summary>
        /// 获取请求的模式
        /// </summary>
        private void GetRequstMode()
        {
            switch (selectedTypeName)
            {
                case "读取一个对象属性请求":
                    RequestMode = ReadMode.GetRequestNormal;
                    break;
                case "读取多个对象属性请求":
                    RequestMode = ReadMode.GetRequestNormalList;
                    break;
                case "设置一个对象属性请求":
                    RequestMode = SetMode.SetRequestNormal;
                    break;
                case "设置多个对象属性请求":
                    RequestMode = SetMode.SetRequestNormalList;
                    break;
                case "设置后读取多个对象属性请求":
                    RequestMode = SetMode.SetThenGetRequestNormalList;
                    break;
                case "操作一个对象方法请求":
                    RequestMode = ActionMode.ActionRequest;
                    break;
            }
        }
        /// <summary>
        /// 根据选择的类型来生成下拉框的选择数据
        /// </summary>
        private void GetComboBoxDataChoiceData()
        {
            DataChoiceList?.Clear();
            BtnReadVisibility = false;
            switch (listBoxType)
            {
                case 0:
                    DataChoiceList.Add("读取一个对象属性请求");
                    DataChoiceList.Add("读取多个对象属性请求");
                    break;
                case 1:
                    DataChoiceList.Add("设置一个对象属性请求");
                    DataChoiceList.Add("设置多个对象属性请求");
                    DataChoiceList.Add("设置后读取多个对象属性请求");
                    BtnReadVisibility = true;
                    break;
                case 2:
                    DataChoiceList.Add("操作一个对象方法请求");
                    DataChoiceList.Add("操作若干个对象方法请求");
                    DataChoiceList.Add("操作若干个对象方法后读取若干个对象属性请求");

                    break;
                case 3:
                    DataChoiceList.Add("建立应用连接");

                    break;
                case 4:
                    DataChoiceList.Add("断开应用连接");

                    break;
                default:
                    break;
            }
            SelectedType = 0;
            if (SelectedObject == null)
            {
                SelectedObject = 0;
            }

        }
        /// <summary>
        /// 刷新ObjectId的列表数据
        /// </summary>
        private void UpdateDataGird()
        {

            //添加数据
            List<ObjectID> listobject;
            if (selectedClassId == 0)
            {
                if (listBoxType == 3)
                {

                    listobject = SqlSugarHelper.Db.Queryable<ObjectID>().Where(o => o.ClientAPDU == 2).OrderBy(o => o._ObjectID).OrderBy(o => o.AttributeID).ToList();
                }
                else if (listBoxType == 4)
                {
                    listobject = SqlSugarHelper.Db.Queryable<ObjectID>().Where(o => o.ClientAPDU == 3).OrderBy(o => o._ObjectID).OrderBy(o => o.AttributeID).ToList();
                }
                else
                {
                    listobject = SqlSugarHelper.Db.Queryable<ObjectID>().Where(o => o.ClientAPDU == (listBoxType + 5)).OrderBy(o => o._ObjectID).OrderBy(o => o.AttributeID).ToList();
                }

            }
            else
            {
                listobject = SqlSugarHelper.Db.Queryable<ObjectID>().Where(o => o.Classid == selectedClassId).Where(o => o.ClientAPDU == (listBoxType + 5)).OrderBy(o => o._ObjectID).OrderBy(o => o.AttributeID).ToList();
            }
            ObjectIdList = new ObservableCollection<ObjectID>(listobject);
        }
        
        /// <summary>
        /// 获取选择抄读的OAD
        /// </summary>
        /// <returns></returns>
        private List<string> GetReadOADSeleced()
        {
            /*List<string> OADSeleced = new List<string>();

            foreach (var item in ObjectIdList)
            {
                if (item.IsSelect == true)
                {
                    OADSeleced.Add(item._ObjectID + ((int)item.AttributeID).ToString("X2") + "00");
                }
            }*/
            


            return ObjectIdList
                .Where(item => item.IsSelect == true)
                .Select(x => x._ObjectID + ((int)x.AttributeID).ToString("X2") + "00")
                .ToList();
        }
        /// <summary>
        /// 获取该OAD的所有设置项
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private List<GWCmdMakeUp> getGWCmdMakeUpList(ObjectID objectID)
        {

            if (objectID == null)
            {
                return null;
            }

            return gWCmdMakeUpService.Select(objectID);
        }
        /// <summary>
        /// 生成设置参数
        /// </summary>
        /// <param name="gWCmdMakeUp"></param>
        /// <returns></returns>
        private string GetSetValue(GWCmdMakeUp gWCmdMakeUp)
        {
            StringBuilder sb = new StringBuilder();
            int? dataFormat = gWCmdMakeUp.DataFormat;
            string Value = gWCmdMakeUp.DataValue;
            string temp = "";
            var Vs = Value.Split(';');
            if (Vs.Length>1)
            {
                for (int i = 0; i < Vs.Length; i++)
                {
                    if (Vs[i].Contains("0x"))
                    {
                        temp = Convert.ToInt64(Vs[i].Replace("0x", ""), 16).ToString();
                    }
                    else
                    {
                        temp = Vs[i];
                    }
                    sb.Append(temp);
                    sb.Append(";");
                }
                Value = sb.ToString().TrimEnd(';');
            }
            else
            {
                Value = gWCmdMakeUp.DataValue;
                if (Value.Contains("0x"))
                {
                    Value = Convert.ToInt64(Value.Replace("0x", ""), 16).ToString();
                }
            }


            string result = "";
            string[] strings = null;
            string[] datas = null;
            
            int num = 0;
            byte data8;
            Int32 data32;
            int parData;
            switch (dataFormat)
            {
                case -1:
                    switch (gWCmdMakeUp.SubItemName)
                    {
                        case "设备地理位置":
                            strings = Value.Split(';');
                            result = "0203";
                            for (int i = 0; i < 2; i++)
                            {
                                result += "020416";
                                result += strings[4 * i].PadLeft(2, '0');
                                result += "16";
                                result += strings[4 * i + 1].PadLeft(2, '0');
                                result += "16";
                                result += strings[4 * i + 2].PadLeft(2, '0');
                                result += "16";
                                result += strings[4 * i + 3].PadLeft(2, '0');
                            }
                            result += "06";
                            result += Int32.Parse(strings[8]).ToString("X8");
                            break;
                        case "本次电能表/交流采样装置配置内容":
                            strings = Value.Split(';');
                            result = "020412";
                            result += (int.Parse(strings[0])).ToString("X4");
                            result += "020A55";
                            if (strings[1].Length % 2 != 0)
                            {
                                strings[1] = strings[1].PadRight(strings[1].Length + 1, 'F');
                            }
                            result += (strings[1].Length / 2 + 1).ToString("X2");
                            result += (strings[1].Length / 2 - 1).ToString("X2");
                            result += strings[1];
                            result += "16";
                            if (strings[2].Equals("11"))
                            {
                                result += "FF";
                            }
                            else
                            {
                                result += (int.Parse(strings[2])).ToString("X2");
                            }
                            result += "16";
                            result += (int.Parse(strings[3]) + 1).ToString("X2");
                            result += "51";
                            result += strings[4];
                            result += "09";
                            if (strings[5].Length % 2 != 0)
                            {
                                strings[5] = strings[5].PadLeft(strings[5].Length + 1, '0');
                            }
                            result += (strings[5].Length / 2).ToString("X2");
                            result += strings[5];
                            result += "11";
                            result += int.Parse(strings[6]).ToString("X2");
                            result += "11";
                            result += int.Parse(strings[7]).ToString("X2");
                            result += "16";
                            result += int.Parse(strings[8]).ToString("X2");
                            result += "12";
                            result += ((int)(double.Parse(strings[9]) * 10)).ToString("X4");
                            result += "12";
                            result += ((int)(double.Parse(strings[10]) * 10)).ToString("X4");

                            result += "020455";
                            if (strings[11].Length % 2 != 0)
                            {
                                strings[11] = strings[11].PadRight(strings[11].Length + 1, 'F');
                            }
                            result += (strings[11].Length / 2 + 1).ToString("X2");
                            result += (strings[11].Length / 2 - 1).ToString("X2");
                            result += strings[11];
                            result += "09";
                            if (strings[12].Length % 2 != 0)
                            {
                                strings[12] = strings[12].PadLeft(6, '0');
                            }
                            result += (strings[12].Length / 2).ToString("X2");
                            result += strings[12];
                            result += "12";
                            result += int.Parse(strings[13]).ToString("X4");
                            result += "12";
                            result += int.Parse(strings[14]).ToString("X4");

                            result += "0100";
                            /*var csdDatas = strings[15].Split(',');
                            num = csdDatas.Length / 2;
                            result += "01";
                            result += num.ToString("X2");
                            for (int i = 0; i < num; i++)
                            {
                                result += "020251";
                                result += csdDatas[2*i].PadLeft(8,'0');
                                result += csdDatas[2*i+1].PadLeft(2, '0');
                            }*/
                            break;
                        case "任务配置表":
                            strings = Value.Split(';');
                            result = "020C11";
                            result += (int.Parse(strings[0])).ToString("X2");
                            result += "54";
                            result += (int.Parse(strings[1])).ToString("X2");
                            result += (int.Parse(strings[2])).ToString("X4");
                            result += "16";
                            result += (int.Parse(strings[3]) + 1).ToString("X2");
                            result += "11";
                            result += (int.Parse(strings[4])).ToString("X2");
                            DateTime startDateTime = DateTime.Parse(strings[5]);
                            result += "1C";
                            result += startDateTime.Year.ToString("X4");
                            result += startDateTime.Month.ToString("X2");
                            result += startDateTime.Day.ToString("X2");
                            result += startDateTime.Hour.ToString("X2");
                            result += startDateTime.Minute.ToString("X2");
                            result += startDateTime.Second.ToString("X2");
                            DateTime endDateTime = DateTime.Parse(strings[6]);
                            result += "1C";
                            result += endDateTime.Year.ToString("X4");
                            result += endDateTime.Month.ToString("X2");
                            result += endDateTime.Day.ToString("X2");
                            result += endDateTime.Hour.ToString("X2");
                            result += endDateTime.Minute.ToString("X2");
                            result += endDateTime.Second.ToString("X2");
                            result += "54";
                            result += (int.Parse(strings[7])).ToString("X2");
                            result += (int.Parse(strings[8])).ToString("X4");
                            result += "11";
                            result += (int.Parse(strings[9])).ToString("X2");
                            result += "16";
                            result += (int.Parse(strings[10]) + 1).ToString("X2");
                            result += "12";
                            result += (int.Parse(strings[11])).ToString("X4");
                            result += "12";
                            result += (int.Parse(strings[12])).ToString("X4");
                            result += "020216";
                            result += (int.Parse(strings[13]) + 1).ToString("X2");
                            if (strings.Length>=15)
                            {
                                var csdDatas = strings[14]?.Split(',');
                                num = csdDatas.Length / 4;
                                result += "01";
                                result += num.ToString("X2");
                                for (int i = 0; i < num; i++)
                                {
                                    result += "020411";
                                    result += int.Parse(csdDatas[4 * i]).ToString("X2");
                                    result += "11";
                                    result += int.Parse(csdDatas[4 * i + 1]).ToString("X2");
                                    result += "11";
                                    result += int.Parse(csdDatas[4 * i + 2]).ToString("X2");
                                    result += "11";
                                    result += int.Parse(csdDatas[4 * i + 3]).ToString("X2");
                                }
                            }
                            else
                            {
                                result += "0100";
                            }
                            break;
                        case "当前套日时段表":
                        case "备用套日时段表":
                            strings = Value.Split(';');
                            result = "01";
                            result += strings.Length.ToString("X2");
                            
                            for (int i = 0; i < strings.Length; i++)
                            {
                                datas= strings[i].Split(",");
                                result += "01";
                                result += (datas.Length/3).ToString("X2");
                                for (int j = 0; j < datas.Length/3; j++)
                                {
                                    result += "020311";
                                    result += (int.Parse(datas[3*j])).ToString("x2");
                                    result += "11";
                                    result += (int.Parse(datas[3*j+1])).ToString("x2");
                                    result += "11";
                                    result += (int.Parse(datas[3*j+2])).ToString("x2");
                                }
                            }
                            break;
                        case "串口":
                        case "RS485":
                            result = "020351";
                            strings = Value.Split(';');
                            result += strings[0];
                            result += "5F";
                            
                            if(int.TryParse(strings[1], out parData))
                                result += parData.ToString("X2");
                            if (int.TryParse(strings[2], out parData))
                                result += parData.ToString("X2");
                            if (int.TryParse(strings[3], out parData))
                                result += (parData+5).ToString("X2");
                            if (int.TryParse(strings[4], out parData))
                                result += (parData + 1).ToString("X2");
                            if (int.TryParse(strings[5], out parData))
                                result += parData.ToString("X2");
                            result += "16";
                            if (int.TryParse(strings[6], out parData))
                                result += parData.ToString("X2");
                            break;
                        case "红外":
                            result = "020251";
                            strings = Value.Split(';');
                            result += strings[0];
                            result += "5F";
                            
                            if (int.TryParse(strings[1], out parData))
                                result += parData.ToString("X2");
                            if (int.TryParse(strings[2], out parData))
                                result += parData.ToString("X2");
                            if (int.TryParse(strings[3], out parData))
                                result += (parData + 5).ToString("X2");
                            if (int.TryParse(strings[4], out parData))
                                result += (parData + 1).ToString("X2");
                            if (int.TryParse(strings[5], out parData))
                                result += parData.ToString("X2");
                            break;
                        case "普通采集方案":
                            if (gWCmdMakeUp.ObjectIdentifier.Equals("60147F00"))
                            {
                                result = "020611";
                                strings = Value.Split(';');
                                result += int.Parse(strings[0]).ToString("X2");
                                result += "12";
                                result += int.Parse(strings[1]).ToString("X4");
                                result += "020211";
                                result += int.Parse(strings[2]).ToString("X2");
                                switch (int.Parse(strings[2]))
                                {
                                    case 0:
                                    case 2:
                                        result += "00";
                                        datas = strings[3].Split(',');
                                        num = datas.Length / 2;
                                        if (num > 0)
                                        {
                                            result += "01";
                                            result += num.ToString("X2");
                                            for (int i = 0; i < num; i++)
                                            {
                                                result += "5B";
                                                result += datas[2 * i];
                                                result += datas[2 * i + 1];
                                            }
                                        }
                                        else
                                        {
                                            result += "00";
                                        }
                                        result += "5C";
                                        result += strings[4];
                                        result += "16";
                                        result += int.Parse(strings[5]).ToString("X2");
                                        break;
                                    case 1:
                                        result += "11";
                                        result += int.Parse(strings[3]).ToString("X2");
                                        datas = strings[4].Split(',');
                                        num = datas.Length / 2;
                                        if (num > 0)
                                        {
                                            result += "01";
                                            result += num.ToString("X2");
                                            for (int i = 0; i < num; i++)
                                            {
                                                result += "5B";
                                                result += datas[2 * i];
                                                result += datas[2 * i + 1];
                                            }
                                        }
                                        else
                                        {
                                            result += "00";
                                        }
                                        result += "5C";
                                        result += strings[5];
                                        result += "16";
                                        result += int.Parse(strings[6]).ToString("X2");
                                        break;
                                    case 3:
                                        result += "54";
                                        result += int.Parse(strings[3]).ToString("X2");
                                        result += int.Parse(strings[4]).ToString("X4");
                                        
                                        datas = strings[5].Split(',');
                                        num = datas.Length / 2;
                                        if (num > 0)
                                        {
                                            result += "01";
                                            result += num.ToString("X2");
                                            for (int i = 0; i < num; i++)
                                            {
                                                result += "5B";
                                                result += datas[2 * i];
                                                result += datas[2 * i + 1];
                                            }
                                        }
                                        else
                                        {
                                            result += "00";
                                        }
                                        result += "5C";
                                        result += strings[6];
                                        result += "16";
                                        result += int.Parse(strings[7]).ToString("X2");
                                        break;
                                    case 4:
                                        result += "020254";
                                        result += int.Parse(strings[3]).ToString("X2");
                                        result += int.Parse(strings[4]).ToString("X4");
                                        result += "12";
                                        result += int.Parse(strings[5]).ToString("X4");

                                        datas = strings[6].Split(',');
                                        num = datas.Length / 2;
                                        if (num > 0)
                                        {
                                            result += "01";
                                            result += num.ToString("X2");
                                            for (int i = 0; i < num; i++)
                                            {
                                                result += "5B";
                                                result += datas[2 * i];
                                                result += datas[2 * i + 1];
                                            }
                                        }
                                        else
                                        {
                                            result += "00";
                                        }
                                        result += "5C";
                                        result += strings[7];
                                        result += "16";
                                        result += int.Parse(strings[8]).ToString("X2");
                                        break;
                                    default:
                                        break;

                                }
                                

                            }
                            else if (gWCmdMakeUp.ObjectIdentifier.Equals("60167F00"))
                            {
                                result = "020511";
                                strings = Value.Split(';');
                                result += int.Parse(strings[0]).ToString("X2");
                                result += "020211";
                                result += int.Parse(strings[1]).ToString("X2");
                                datas = strings[2].Split(',');
                                num = datas.Length;
                                if (num > 0)
                                {
                                    result += "01";
                                    result += num.ToString("X2");
                                    for (int i = 0; i < num; i++)
                                    {
                                        result += "52";
                                        result += datas[i];
                                    }
                                }
                                else
                                {
                                    result += "00";
                                }
                                result += "5C";
                                result += strings[3];
                                result += "03";
                                result += int.Parse(strings[4]).ToString("X2");
                                result += "12";
                                result += int.Parse(strings[5]).ToString("X4");
                            }
                            break;
                        case "透明方案集":
                            result = "020311";
                            strings = Value.Split(';');
                            result += int.Parse(strings[0]).ToString("X2");
                            datas = strings[1].Split(',');
                            if (datas.Length>0)
                            {
                                result += "020612";
                                result += int.Parse(datas[0]).ToString("X4");
                                result += "55";
                                if (datas[1].Length%2!=0)
                                {
                                    datas[1] = datas[1].PadRight(datas[1].Length+1,'F');
                                }
                                result += (datas[1].Length+1).ToString("X2");
                                result += (datas[1].Length -1).ToString("X2");
                                result += datas[1];
                                result += "12";
                                result += int.Parse(datas[2]).ToString("X4");
                                result += "12";
                                result += int.Parse(datas[3]).ToString("X4");
                                result += "020403";
                                result += int.Parse(datas[4]).ToString("X2");
                                result += "12";
                                result += int.Parse(datas[5]).ToString("X4");
                                result += "16";
                                result += int.Parse(datas[6]).ToString("X2");
                                result += "020311";
                                result += int.Parse(datas[7]).ToString("X2");
                                result += "12";
                                result += int.Parse(datas[8]).ToString("X4");
                                result += "12";
                                result += int.Parse(datas[9]).ToString("X4");
                                if (datas.Length>11)
                                {
                                    result += "01";
                                    num = (datas.Length - 10) / 2;
                                    result += num.ToString("X2");
                                    for (int i = 0; i < num; i++)
                                    {
                                        result += "11";
                                        result += int.Parse(datas[2*i+ 10]).ToString("X2");
                                        result += "09";
                                        result += datas[2 * i + 10+1].Length.ToString("X2");
                                        result += datas[2 * i + 10+1];
                                    }
                                    
                                }
                                else
                                {
                                    result += "00";
                                }
                            }
                            /*else
                            {
                                result += "00";
                            }*/
                            result += "12";
                            result += int.Parse(strings[2]).ToString("X2");
                            break;
                        case "当前套阶梯电价":
                        case "备用套阶梯电价":
                            result = "020301";
                            strings = Value.Split(';');
                            datas = strings[0].Split(',');
                            result += datas.Length.ToString("X2");
                            for (int i = 0; i < datas.Length; i++)
                            {
                                result += "06";
                                result += Int64.Parse(datas[i]).ToString("X8");
                            }
                            result += "01";
                            datas = strings[1].Split(',');
                            result += datas.Length.ToString("X2");
                            for (int i = 0; i < datas.Length; i++)
                            {
                                result += "06";
                                result += Int64.Parse(datas[i]).ToString("X8");
                            }
                            result += "01";
                            datas = strings[2].Split(',');
                            num = datas.Length / 3;
                            result += num.ToString("X2");
                            for (int i = 0; i < num; i++)
                            {
                                result += "020311";
                                result += int.Parse(datas[3*i]).ToString("X2");
                                result += "11";
                                result += int.Parse(datas[3 * i+1]).ToString("X2");
                                result += "11";
                                result += int.Parse(datas[3 * i+2]).ToString("X2");
                            }

                            break;
                        default:
                            break;
                    }
                    break;
                case 1:
                    if (gWCmdMakeUp.SubItemName.Contains("总加配置表"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length / 3;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i += 3)
                        {
                            result += "020355";
                            strings[i] = strings[i].PadRight(strings[i].Length % 2 == 0 ? strings[i].Length : strings[i].Length + 1, 'F');
                            result += (1 + strings[i].Length / 2).ToString("X2");
                            result += (strings[i].Length / 2 - 1).ToString("X2");
                            result += strings[i];
                            result += "16";
                            result += strings[i + 1].PadLeft(2, '0');
                            result += "16";
                            result += strings[i + 2].PadLeft(2, '0');
                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Contains("关联对象属性表"))
                    {
                        if (gWCmdMakeUp.Remark.Split(';').Length == 3)
                        {
                            strings = Value.Split(';');
                            num = strings.Length / 3;
                            result = num.ToString("X2");
                            if (num <= 0)
                            {
                                break;
                            }
                            for (int i = 0; i < strings.Length; i += 3)
                            {
                                result += "020312";
                                result += Int16.Parse(strings[i]).ToString("X4");
                                result += "51";
                                result += strings[i + 1].PadLeft(8, '0');
                                result += "12";
                                result += Int16.Parse(strings[i + 2]).ToString("X4");
                            }
                        }
                        else
                        {
                            strings = Value.Split(';');
                            num = strings.Length;
                            result = num.ToString("X2");
                            for (int i = 0; i < strings.Length; i++)
                            {
                                result += "51";
                                result += strings[i].PadLeft(8, '0');
                            }
                        }

                    }

                    else if (gWCmdMakeUp.SubItemName.Contains("脉冲配置"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length / 3;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i += 3)
                        {
                            result += "020351";
                            result += strings[i].PadLeft(8, '0');
                            result += "16";
                            result += Byte.Parse(strings[i + 1]).ToString("X2");
                            result += "12";
                            result += Int16.Parse(strings[i + 2]).ToString("X4");
                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Equals("协议通道切换")|| gWCmdMakeUp.SubItemName.Equals("主站通信参数表") || gWCmdMakeUp.SubItemName.Contains("主站通讯参数"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length / 2;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i += 2)
                        {
                            result += "02020904";
                            datas = strings[i].Split('.');
                            for (int j = 0; j < datas.Length; j++)
                            {
                                result += Int16.Parse(datas[j]).ToString("X2");
                            }

                            result += "12";
                            result += Int32.Parse(strings[i + 1]).ToString("X4");
                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Contains("公共假日表"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length / 2;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i += 2)
                        {
                            result += "02021A";
                            short.TryParse(strings[i].Substring(0, 4), out short year);
                            byte.TryParse(strings[i].Substring(4, 2), out byte month);
                            byte.TryParse(strings[i].Substring(6, 2), out byte day);
                            byte.TryParse(strings[i].Substring(8, 2), out byte hour);

                            result += year.ToString("X4") + month.ToString("X2") + day.ToString("X2") +
                                hour.ToString("X2");
                            result += "11";
                            if (byte.TryParse(strings[i + 1], out byte obyte))
                            {
                                result += obyte.ToString("X2");
                            }

                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Contains("组地址"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i++)
                        {
                            result += "09";
                            strings[i] = strings[i].PadLeft(strings[i].Length % 2 == 0 ? strings[i].Length : strings[i].Length + 1, '0');
                            result += (strings[i].Length / 2).ToString("X2");
                            result += strings[i];

                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Contains("时区表"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length / 3;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i += 3)
                        {
                            result += "020311";

                            if (byte.TryParse(strings[i], out data8))
                            {
                                result += data8.ToString("X2");
                            }
                            result += "11";
                            if (byte.TryParse(strings[i + 1], out data8))
                            {
                                result += data8.ToString("X2");
                            }
                            result += "11";
                            if (byte.TryParse(strings[i + 2], out data8))
                            {
                                result += data8.ToString("X2");
                            }
                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Contains("费率电价"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i++)
                        {
                            result += "06";
                            if (Int32.TryParse(strings[i], out data32))
                            {
                                result += data32.ToString("X8");
                            }

                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Contains("结算日"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length / 2;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i += 2)
                        {
                            result += "020211";
                            if (byte.TryParse(strings[i], out data8))
                            {
                                result += data8.ToString("X2");
                            }
                            result += "11";
                            if (byte.TryParse(strings[i + 1], out data8))
                            {
                                result += data8.ToString("X2");
                            }

                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Contains("支持规约列表"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length ;
                        result = num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i ++)
                        {
                            result += "0A";
                            result += strings[i].Length.ToString("X2") + StringUtils.StringToASCII(strings[i]);

                        }
                    }
                    else if(gWCmdMakeUp.SubItemName.Contains("侦听端口列表"))
                    {
                        strings = Value.Split(';');
                        num = strings.Length;
                        result += num.ToString("X2");
                        if (num <= 0)
                        {
                            break;
                        }
                        for (int i = 0; i < strings.Length; i++)
                        {
                            result += "12";
                            result += int.Parse(strings[i]).ToString("X4");

                        }
                    }
                    else if (gWCmdMakeUp.SubItemName.Equals("参数"))
                    {
                        switch (gWCmdMakeUp.ObjectIdentifier)
                        {
                            case "43000400":
                                datas = gWCmdMakeUp.DataValue.Split(';');
                                result = datas.Length.ToString("X2");
                                for (int i = 0; i < datas.Length; i++)
                                {
                                    result += "51";
                                    result += datas[i];
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case 3:
                    if (Value != "0")
                    {
                        result = "01";
                    }
                    else
                    {
                        result = "00";
                    }
                    break;
                case 4:
                    int len = 4 * Value.Length;
                    result = len.ToString("X2") + Value;
                    break;
                case 5:
                    if (Int32.TryParse(Value, out data32))
                    {
                        result = data32.ToString("X8");
                    }
                    break;
                case 6:
                    int data;
                    if (Int32.TryParse(Value, out data))
                    {
                        result = data.ToString("X8");
                    }
                    break;
                case 9:
                    //result = "06" + Value.PadLeft(12, '0');
                    if ((gWCmdMakeUp.SubItemName.Contains("服务器地址")|| gWCmdMakeUp.ObjectIdentifier.Equals("45100400"))&&Value.Contains('.'))
                    {
                        datas = Value.Split('.');
                        result += datas.Length.ToString("X2");
                        for (int i = 0; i < datas.Length; i++)
                        {
                            result += int.Parse(datas[i]).ToString("X2");
                        }
                    }
                    else
                    {
                        result = (Value.Length / 2).ToString("X2") + Value;
                    }
                        

                    break;
                case 0x0a:
                    int valueLen = gWCmdMakeUp.Remark.IndexOf(')') - gWCmdMakeUp.Remark.IndexOf('(') - 1;
                    if (valueLen > 0)
                    {
                        string size = gWCmdMakeUp.Remark.Substring(gWCmdMakeUp.Remark.IndexOf('(') + 1, valueLen);
                        if (size != null)
                        {
                            if (Byte.TryParse(size, out data8))
                            {
                                result = data8.ToString("X2") + StringUtils.StringToASCII(Value).PadRight(data8 * 2, '0');
                            }

                        }
                        else
                        {
                            result = Value.Length.ToString("X2") + StringUtils.StringToASCII(Value);
                        }
                    }
                    else
                    {
                        result = Value.Length.ToString("X2") + StringUtils.StringToASCII(Value);
                    }
                    /*if (gWCmdMakeUp.SubItemName.Contains("管理编码"))
                    {
                        result = "20" + StringUtils.StringToASCII(Value).PadRight(64, '0');
                    }
                    else
                    {
                        result = Value.Length.ToString("X2") + StringUtils.StringToASCII(Value);
                    }*/
                    break;

                case 0x11:
                    if (byte.TryParse(Value, out byte unsignedData))
                    {
                        result = unsignedData.ToString("X2");
                    }
                    break;
                case 0x10:
                case 0x12:
                    if (Int32.TryParse(Value, out data32))
                    {
                        result = data32.ToString("X4");
                    }
                    break;
                case 0x16:
                    result = Value.PadLeft(2, '0');
                    break;
                case 0x1c:
                    if (Value == "系统时间"||string.IsNullOrWhiteSpace(Value))
                    {
                        result = DateTime.Now.Year.ToString("X4") + DateTime.Now.Month.ToString("X2") + DateTime.Now.Day.ToString("X2") +
                            DateTime.Now.Hour.ToString("X2") + DateTime.Now.Minute.ToString("X2") + DateTime.Now.Second.ToString("X2");
                    }
                    else
                    {
                        short.TryParse(Value.Substring(0, 4), out short year);
                        byte.TryParse(Value.Substring(4, 2), out byte month);
                        byte.TryParse(Value.Substring(6, 2), out byte day);
                        byte.TryParse(Value.Substring(8, 2), out byte hour);
                        byte.TryParse(Value.Substring(10, 2), out byte min);
                        byte.TryParse(Value.Substring(10, 2), out byte sec);
                        //var sec = Convert.ToInt16(Value.Substring(12, 2), 16);

                        result = year.ToString("X4") + month.ToString("X2") + day.ToString("X2") +
                            hour.ToString("X2") + min.ToString("X2") + sec.ToString("X2");
                    }
                    break;
                case 0x51:
                    result = Value.PadLeft(8, '0');
                    break;
                case 0x5f:
                    datas = Value.Split(',');
                    result = int.Parse(datas[0]).ToString("X2");
                    result += int.Parse(datas[1]).ToString("X2");
                    result += (int.Parse(datas[2]) + 5).ToString("X2");
                    result += (int.Parse(datas[3]) + 1).ToString("X2");
                    result += int.Parse(datas[4]).ToString("X2");
                    break;
                case 0x65:
                    strings = Value.Split(',');
                    result = "020A55";
                    result += (strings[0].Length / 2 + 1).ToString("X2");
                    result += (strings[0].Length / 2 - 1).ToString("X2");
                    result += strings[0];
                    result += "16";
                    if (strings[1].Equals("11"))
                    {
                        result += "FF";
                    }
                    else
                    {
                        result += (int.Parse(strings[1])).ToString("X2");
                    }
                    result += "16";
                    result += (int.Parse(strings[2]) + 1).ToString("X2");
                    result += "51";
                    result += strings[3];
                    result += "09";
                    result += (strings[4].Length / 2).ToString("X2");
                    result += strings[4];
                    result += "11";
                    result += int.Parse(strings[5]).ToString("X2");
                    result += "11";
                    result += int.Parse(strings[6]).ToString("X2");
                    result += "16";
                    result += int.Parse(strings[7]).ToString("X2");
                    result += "12";

                    result += ((int)(double.Parse(strings[8]) * 10)).ToString("X4");
                    result += "12";
                    result += ((int)(double.Parse(strings[9]) * 10)).ToString("X4");
                    break;
                case 0x66:
                    strings = Value.Split(',');
                    result = "020455";
                    result += (strings[0].Length / 2 + 1).ToString("X2");
                    result += (strings[0].Length / 2 - 1).ToString("X2");
                    result += strings[0];
                    result += "09";
                    result += (strings[1].Length / 2).ToString("X2");
                    result += strings[1];
                    result += "12";
                    result += int.Parse(strings[2]).ToString("X4");
                    result += "12";
                    result += int.Parse(strings[3]).ToString("X4");
                    break;
                case 0x67:
                    result = "0100";
                    break;
                default:
                    break;

            }
            return result;
        }

        /// <summary>
        /// 获取选择设置的OAD及其参数
        /// </summary>
        /// <returns></returns>
        private async Task<Dictionary<string, string>> GetSetOADSeleced()
        {
            Dictionary<string, string> OADSeleced = new Dictionary<string, string>();
            await Task.Run(() =>
            {
                
                string OAD = "";
                StringBuilder Value = new StringBuilder();
                foreach (var item in ObjectIdList)
                {
                    Value.Clear();
                    if (item.IsSelect == true)
                    {
                        var list = getGWCmdMakeUpList(item);
                        /*if (int.TryParse(item.AttributeID.ToString(), out id) == true)
                        {
                            OAD = dataGridViewOAD.Rows[i].Cells[1].Value.ToString() + id.ToString("X2") + "00";
                        }
                        else
                        {
                            break;
                        }*/
                        OAD = item._ObjectID + ((int)item.AttributeID).ToString("X2") + "00";
                        if (list.Count == 1)
                        {
                            GWCmdMakeUp gWCmdMakeUp = list[0];
                            if (gWCmdMakeUp.DataFormat != -1)
                            {
                                Value.Append(((int)gWCmdMakeUp.DataFormat).ToString("X2").PadLeft(2, '0'));
                            }
                            Value.Append(GetSetValue(gWCmdMakeUp));

                        }
                        else if (list.Count > 1)
                        {
                            if (OAD.Equals("60008000"))
                            {
                                ServiceLocator.Current.GetInstance<AddBatchConnectArViewModel>().SaveDataInfo();
                                if (AddBatchConnectArViewModel.GWCmdMakeUp!=null)
                                {
                                    list[(int)AddBatchConnectArViewModel.GWCmdMakeUp.SubItemID - 1] = AddBatchConnectArViewModel.GWCmdMakeUp;
                                }
                                
                                Value.Append("01");
                                Value.Append(ServiceLocator.Current.GetInstance<AddBatchConnectArViewModel>().TotalNum.ToString("X2"));
                                for (int i = 0; i < ServiceLocator.Current.GetInstance<AddBatchConnectArViewModel>().TotalNum; i++)
                                {
                                    var g = list[i];
                                    Value.Append(GetSetValue(g));
                                }
                            }
                            else if (OAD.Equals("60127F00"))
                            {
                                ServiceLocator.Current.GetInstance<AddOrUpdateJobViewModel>().SaveDataInfo();
                                if (AddOrUpdateJobViewModel.GWCmdMakeUp != null)
                                {
                                    list[(int)AddOrUpdateJobViewModel.GWCmdMakeUp.SubItemID - 1] = AddOrUpdateJobViewModel.GWCmdMakeUp;
                                }
                                Value.Append("01");
                                Value.Append(ServiceLocator.Current.GetInstance<AddOrUpdateJobViewModel>().TotalNum.ToString("X2"));
                                for (int i = 0; i < ServiceLocator.Current.GetInstance<AddOrUpdateJobViewModel>().TotalNum; i++)
                                {
                                    var g = list[i];
                                    if (string.IsNullOrEmpty(g.DataValue))
                                    {
                                        MessageBox.Show("数据存在空值");
                                        return;
                                    }
                                    Value.Append(GetSetValue(g));
                                }
                            }
                            else if (OAD.Equals("60147F00"))
                            {
                                ServiceLocator.Current.GetInstance<AddOrUpdateConnectPlanViewModel>().SaveDataInfo();
                                if (AddOrUpdateConnectPlanViewModel.GWCmdMakeUp != null)
                                {
                                    list[(int)AddOrUpdateConnectPlanViewModel.GWCmdMakeUp.SubItemID - 1] = AddOrUpdateConnectPlanViewModel.GWCmdMakeUp;
                                }
                                Value.Append("01");
                                Value.Append(ServiceLocator.Current.GetInstance<AddOrUpdateConnectPlanViewModel>().TotalNum.ToString("X2"));
                                for (int i = 0; i < ServiceLocator.Current.GetInstance<AddOrUpdateConnectPlanViewModel>().TotalNum; i++)
                                {
                                    var g = list[i];
                                    if (string.IsNullOrEmpty(g.DataValue))
                                    {
                                        MessageBox.Show("数据存在空值");
                                        return;
                                    }
                                    Value.Append(GetSetValue(g));
                                }
                            }
                            else if (OAD.Equals("60167F00"))
                            {
                                ServiceLocator.Current.GetInstance<AddOrUpdateEventViewModel>().SaveDataInfo();
                                if (AddOrUpdateEventViewModel.GWCmdMakeUp != null)
                                {
                                    list[(int)AddOrUpdateEventViewModel.GWCmdMakeUp.SubItemID - 1] = AddOrUpdateEventViewModel.GWCmdMakeUp;
                                }
                                Value.Append("01");
                                Value.Append(ServiceLocator.Current.GetInstance<AddOrUpdateEventViewModel>().TotalNum.ToString("X2"));
                                for (int i = 0; i < ServiceLocator.Current.GetInstance<AddOrUpdateEventViewModel>().TotalNum; i++)
                                {
                                    var g = list[i];
                                    if (string.IsNullOrEmpty(g.DataValue))
                                    {
                                        MessageBox.Show("数据存在空值");
                                        return;
                                    }
                                    Value.Append(GetSetValue(g));
                                }
                            }
                            else
                            {
                                Value.Append("02");
                                Value.Append(list.Count.ToString("X2").PadLeft(2, '0'));
                                list.ForEach(g =>
                                {
                                    if (g.DataFormat != -1 && g.DataFormat != 0x65 && g.DataFormat != 0x66 && g.DataFormat != 0x67)
                                    {
                                        Value.Append(((int)g.DataFormat).ToString("X2").PadLeft(2, '0'));
                                    }
                                    Value.Append(GetSetValue(g));
                                });
                            }

                        }
                        else
                        {
                            Console.WriteLine("无数据项");
                            break;
                        }
                        OADSeleced.Add(OAD, Value.ToString());
                    }
                }
                
            });
            return OADSeleced;
        }
        private void ReadRequest(ReadMode mode, List<string> OADSeleced, string DeviceAddress, int SecuritySelected)
        {

            //ReadMode mode = (ReadMode)RequestMode;
            if (mode == ReadMode.GetRequestNormal)
            {
                cts = new CancellationTokenSource();
                MainTask = Task.Run(async () =>
                {
                    foreach (var OAD in OADSeleced)
                    {
                        if (cts.Token.IsCancellationRequested)
                        {
                            Messenger.Default.Send<string>($"通讯停止({DateTime.Now.ToString()})\r\n", "StopMessage");
                            break;
                        }

                        while (true)
                        {
                            byte[] b = MessageGeneration(DeviceAddress, mode, OAD, SecuritySelected);
                            sendMessageShow(b);
                            //serialPortHelper.SendDataMethod(b);
                            //bool result = false;
                            //await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            //await sendMessageAsync(DeviceAddress, b);
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    bool result = false;
                                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                                    break;
                                case "GPRS":

                                    tcpHelper.isComplete = false;
                                    tcpHelper.SendData(DeviceAddress, b);
                                    await awitTCPRecv(5);

                                    break;
                                default:
                                    break;
                            }
                            //Console.WriteLine(result);
                            break;
                        }

                    }
                }, cts.Token);

            }
            else if (mode == ReadMode.GetRequestNormalList)
            {
                MainTask = Task.Run(async () =>
                {
                    string OADs = "";
                    foreach (var OAD in OADSeleced)
                    {
                        OADs += OAD;
                    }
                    byte[] b = MessageGeneration(DeviceAddress, mode, OADs, SecuritySelected);
                    sendMessageShow(b);
                    //bool result = false;
                    await sendMessageAsync(DeviceAddress, b);

                });

            }
        }
        private void SetRequest(Dictionary<string, string> map, string DeviceAddress, int SecuritySelected)
        {
            SetMode mode = (SetMode)RequestMode;
            if (mode == SetMode.SetRequestNormal)
            {
                cts = new CancellationTokenSource();
                MainTask = Task.Run(async () =>
                {
                    foreach (var item in map)
                    {
                        Dictionary<string, string> sendOADData = new Dictionary<string, string>
                        {
                            { item.Key, item.Value }
                        };
                        if (cts.Token.IsCancellationRequested)
                        {
                            Messenger.Default.Send<string>($"通讯停止({DateTime.Now.ToString()})\r\n", "StopMessage");
                            break;
                        }

                        while (true)
                        {
                            byte[] b = MessageGeneration(DeviceAddress, mode, sendOADData, SecuritySelected);
                            sendMessageShow(b);
                            /*serialPortHelper.SendDataMethod(b);
                            bool result = false;
                            await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            Console.WriteLine(result);*/
                            //await sendMessageAsync(DeviceAddress, b);
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    bool result = false;
                                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                                    break;
                                case "GPRS":

                                    tcpHelper.isComplete = false;
                                    tcpHelper.SendData(DeviceAddress, b);
                                    await awitTCPRecv(5);

                                    break;
                                default:
                                    break;
                            }
                            break;

                        }

                    }
                }, cts.Token);

            }
            else if (mode == SetMode.SetRequestNormalList)
            {
                MainTask = Task.Run(async () =>
                {
                    byte[] b = MessageGeneration(DeviceAddress, mode, map, SecuritySelected);
                    sendMessageShow(b);
                    //await sendMessageAsync(DeviceAddress, b);
                    switch (CommViewModel.selectedCommType)
                    {
                        case "串口":
                            serialPortHelper.SendDataMethod(b);
                            bool result = false;
                            await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                            break;
                        case "GPRS":

                            tcpHelper.isComplete = false;
                            tcpHelper.SendData(DeviceAddress, b);
                            await awitTCPRecv(5);

                            break;
                        default:
                            break;
                    }
                    /*serialPortHelper.SendDataMethod(b);
                    bool result = false;
                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());*/
                    //Console.WriteLine(result);
                });


            }
            else if (mode == SetMode.SetThenGetRequestNormalList)
            {

            }
        }
        private void ActionRequest(Dictionary<string, string> map, string DeviceAddress, int SecuritySelected)
        {
            ActionMode mode = (ActionMode)RequestMode;
            if (mode == ActionMode.ActionRequest)
            {
                cts = new CancellationTokenSource();
                MainTask = Task.Run(async () =>
                {
                    foreach (var item in map)
                    {
                        Dictionary<string, string> sendOADData = new Dictionary<string, string>
                        {
                            { item.Key, item.Value }
                        };
                        if (cts.Token.IsCancellationRequested)
                        {
                            Messenger.Default.Send<string>($"通讯停止({DateTime.Now.ToString()})\r\n", "StopMessage");
                            break;
                        }

                        while (true)
                        {
                            byte[] b = MessageGeneration(DeviceAddress, mode, sendOADData, SecuritySelected);
                            sendMessageShow(b);
                            //await sendMessageAsync(DeviceAddress, b);
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    bool result = false;
                                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                                    break;
                                case "GPRS":

                                    tcpHelper.isComplete = false;
                                    tcpHelper.SendData(DeviceAddress, b);
                                    await awitTCPRecv(5);

                                    break;
                                default:
                                    break;
                            }
                            //serialPortHelper.SendDataMethod(b);
                            //bool result = false;
                            //await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            //Console.WriteLine(result);
                            break;

                        }

                    }
                }, cts.Token);

            }
            else if (mode == ActionMode.ActionRequest)
            {
                MainTask = Task.Run(async () =>
                {
                    byte[] b = MessageGeneration(DeviceAddress, mode, map, SecuritySelected);
                    sendMessageShow(b);
                    //await sendMessageAsync(DeviceAddress, b);
                    switch (CommViewModel.selectedCommType)
                    {
                        case "串口":
                            serialPortHelper.SendDataMethod(b);
                            bool result = false;
                            await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                            break;
                        case "GPRS":

                            tcpHelper.isComplete = false;
                            tcpHelper.SendData(DeviceAddress, b);
                            await awitTCPRecv(5);

                            break;
                        default:
                            break;
                    }
                    /*serialPortHelper.SendDataMethod(b);
                    bool result = false;
                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                    Console.WriteLine(result);*/
                });

            }
            else if (mode == ActionMode.ActionThenGetRequestNormalList)
            {

            }
        }
        private void Connect(string DeviceAddress)
        {
            StateGridClient sc = ServiceLocator.Current.GetInstance<MainViewModel>().sc;
            ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = false;
            cts = new CancellationTokenSource();
            MainTask = Task.Run(async () =>
            {
                string data = "";
                SessionInit = "";
                Sign = "";
                SessionInitKey = "";

                string cOutSessionInit = "";
                string cOutSign;
                if (string.IsNullOrWhiteSpace(ESAMDiv) || string.IsNullOrWhiteSpace(ESAMCounter))
                {
                    MessageBox.Show("请先获取ESAM信息");
                    return;
                }
                try
                {
                    
                    if (sc.State == CommunicationState.Closed)
                    {
                        /*Config config = XmlHelper.Deserializer<Config>("Config.xml");
                        try
                        {
                            if (config != null)
                            {
                                System.ServiceModel.Channels.Binding binding = new NetTcpBinding(SecurityMode.None, true);
                                //EndpointAddress endpoint = new EndpointAddress("net.tcp://10.1.2.32:10010/StateGrid/");
                                EndpointAddress endpoint = new EndpointAddress(config.EndpointAddress);
                                sc = new StateGridClient(binding, endpoint);
                            }
                            else
                            {
                                MessageBox.Show("获取加密机服务地址错误,请检查配置文件是否正确");
                            }
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("获取加密机服务地址错误,请检查配置文件是否正确");
                        }*/
                        System.ServiceModel.Channels.Binding binding = new NetTcpBinding(SecurityMode.None, true);
                        //EndpointAddress endpoint = new EndpointAddress("net.tcp://10.1.2.32:10010/StateGrid/");
                        //EndpointAddress endpoint = new EndpointAddress(config.EndpointAddress);
                        EndpointAddress endpoint = new EndpointAddress(EncryptorSettings.Instanse.EndpointAddress);
                        sc = new StateGridClient(binding, endpoint);

                    }
                    //string cOutRandHost = "";
                    int r = 0;
                    string authenticationFlag = "";
                    string Counter = (Convert.ToInt64(ESAMCounter) + 1).ToString("X8");
                    iKeyState = 0;
                    if (ESAMVersion.Contains("7FFFFFFFF"))
                    {
                        iKeyState = 1;
                    }

                    if (MainViewModel.selectedDevice.DeviceType.Equals("集中器"))
                    {
                        if (string.IsNullOrWhiteSpace(MasterCert))
                        {
                            ReadRequest(ReadMode.GetRequestNormal, new List<string> { "F1000C00" }, DeviceAddress,0);
                            Thread.Sleep(1000);
                            if (string.IsNullOrWhiteSpace(MasterCert))
                            {
                                MessageBox.Show("获取证书失败");
                                return;
                            }
                        }
                        authenticationFlag = "03";
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务中...", "Info");
                        r = sc.Obj_Terminal_Formal_InitSession(iKeyState, ESAMDiv, Counter, "01", MasterCert, out cOutRandHost, out cOutSessionInit, out cOutSign);
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务完成", "Info");
                    }
                    else
                    {
                        authenticationFlag = "02";
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务中...", "Info");
                        r = sc.Obj_Meter_Formal_InitSession(iKeyState, ESAMDiv, Counter, "01", out cOutRandHost, out cOutSessionInit, out cOutSign);
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务完成", "Info");
                    }
                    //sc.Obj_Terminal_Formal_GetCACertificateData(iKeyState, ESAMDiv, Counter, "01");
                    //r = sc.Obj_Meter_Formal_InitSession(iKeyState, ESAMDiv, Counter, "01", out string cOutRandHost, out string cOutSessionInit, out string cOutSign);
                    //r = sc.Obj_Terminal_Formal_InitSession(iKeyState, ESAMDiv, Counter, "01", MasterCert, out string cOutRandHost, out string cOutSessionInit, out string cOutSign);
                    if (r == 0)
                    {
                        ObjectID objectID = objectIDService.Select(2);
                        gWCmdMakeUpSelected = gWCmdMakeUpService.Select(objectID)[0];
                        var strings = gWCmdMakeUpSelected.DataValue.Split(';');
                        data += strings[0].PadLeft(4, '0');
                        data += strings[1].PadRight(16, '0');
                        data += strings[2].PadRight(32, '0');
                        data += Convert.ToInt16(strings[3]).ToString("X4");
                        data += Convert.ToInt16(strings[4]).ToString("X4");
                        data += strings[5].PadLeft(2, '0');
                        data += Convert.ToInt16(strings[6]).ToString("X4");
                        data += Convert.ToInt32(strings[7]).ToString("X8");
                        //data += Convert.ToByte(strings[8]).ToString("X2");
                        data += authenticationFlag;
                        data += ((cOutSessionInit.Length / 2).ToString("X2") + cOutSessionInit + (cOutSign.Length / 2).ToString("X2") + cOutSign);
                        byte[] b = MessageGeneration(ConnectMode.Connect, DeviceAddress, data, 0);
                        sendMessageShow(b);
                        switch (CommViewModel.selectedCommType)
                        {
                            case "串口":
                                serialPortHelper.SendDataMethod(b);
                                bool result = false;
                                await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                                if (result)
                                {
                                    if (string.IsNullOrWhiteSpace(SessionInit) || string.IsNullOrWhiteSpace(Sign))
                                    {
                                        //MessageBox.Show("获取应用连接数据失败");
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取应用连接数据失败", "Info");
                                        return;
                                    }
                                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务中...", "Info");
                                    r = sc.Obj_Meter_Formal_VerifySession(iKeyState, ESAMDiv, cOutRandHost, SessionInit, Sign, out SessionInitKey);
                                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务完成", "Info");
                                    if (r == 0)
                                    {
                                        ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = true;
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：连接成功", "Info");
                                        //MessageBox.Show("连接成功");
                                    }
                                    else
                                    {
                                        //MessageBox.Show($"获取加密数据失败，错误码：{r}");
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取加密数据失败，错误码：{r}", "Info");
                                    }
                                }
                                break;
                            case "GPRS":
                                tcpHelper.isComplete = false;
                                tcpHelper.SendData(DeviceAddress, b);
                                //await Task.Delay(1000);
                                await awitTCPRecv(5);
                                if (tcpHelper.isComplete == true)
                                {
                                    if (string.IsNullOrWhiteSpace(SessionInit) || string.IsNullOrWhiteSpace(Sign))
                                    {
                                        //MessageBox.Show("获取应用连接数据失败");
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取应用连接数据失败", "Info");
                                        return;
                                    }
                                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务中...", "Info");
                                    r = sc.Obj_Terminal_Formal_VerifySession(iKeyState, ESAMDiv, cOutRandHost, SessionInit, Sign, TerminalCert, out SessionInitKey);
                                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务完成", "Info");
                                    if (r == 0)
                                    {
                                        ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = true;
                                        //MessageBox.Show("连接成功");
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：连接成功", "Info");
                                    }
                                    else
                                    {
   
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取加密数据失败，错误码：{r}", "Info");
                                    }
                                }
                                break;
                            default:
                                break;
                        }

                    }
                    else
                    {
                        //MessageBox.Show($"获取加密数据失败，错误码：{r}");
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取加密数据失败，错误码：{r}", "Info");
                    }
                }
                catch (Exception)
                {
                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务失败，服务器无响应", "Info");
                    sc.Close();
                    
                    return;
                }

            }, cts.Token);
        }
        private void DisConnect(string DeviceAddress)
        {
            cts = new CancellationTokenSource();
            MainTask = Task.Run(async () =>
            {

                try
                {
                    byte[] b = MessageGeneration(ConnectMode.DisConnect, DeviceAddress, "", 0);
                    sendMessageShow(b);
                    switch (CommViewModel.selectedCommType)
                    {
                        case "串口":
                            serialPortHelper.SendDataMethod(b);
                            bool result = false;
                            await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            if (result == true)
                            {
                                ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = false;
                            }
                            break;
                        case "GPRS":

                            tcpHelper.isComplete = false;
                            tcpHelper.SendData(DeviceAddress, b);
                            await awitTCPRecv(5);
                            if (tcpHelper.isComplete == true)
                            {
                                ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = false;
                            }
                            break;
                        default:
                            break;
                    }

                }
                catch (Exception e1)
                {

                    MessageBox.Show(e1.Message);
                    return;
                }

            }, cts.Token);
        }
        /// <summary>
        /// 发送帧显示
        /// </summary>
        /// <param name="b"></param>
        private void sendMessageShow(byte[] b)
        {
            string msgStr = "";
            for (int i = 0; i < b.Length; i++)
            {
                msgStr += b[i].ToString("X2") + " ";
            }
            Messenger.Default.Send<string>($"发送帧({DateTime.Now.ToString()})：{msgStr}", "SendMessage");
        }
        private async Task sendMessageAsync(string address, byte[] b)
        {
            switch (CommViewModel.selectedCommType)
            {
                case "串口":
                    serialPortHelper.SendDataMethod(b);
                    await Task.Run(() => serialPortHelper.DataReceiveFunction());
                    break;
                case "GPRS":
                    tcpHelper.SendData(address, b);
                    break;
                default:
                    break;
            }
        }

        private async Task awitTCPRecv(int timeOutSec)
        {
            using (var tokenSource = new CancellationTokenSource())
            {

                var startTime = DateTime.Now;
                while (true)
                {
                    if ((DateTime.Now - startTime) >= TimeSpan.FromSeconds(timeOutSec))
                    {
                        tokenSource.Cancel();
                    }
                    if (tokenSource.IsCancellationRequested)
                    {
                        return;
                    }
                    if (tcpHelper.isComplete == true)
                    {
                        return;
                    }
                    await Task.Delay(TimeSpan.FromMilliseconds(10));
                }
            }
        }
        #endregion
        #region command
        public RelayCommand SendCommand
        {
            get
            {
                var command = new RelayCommand(async () =>
                {

                    if (MainViewModel.selectedDevice == null)
                    {
                        MessageBox.Show("请选择设备");
                        return;
                    }
                    if (!MainViewModel.state)
                    {
                        MessageBox.Show("请先打开通道");
                        return;
                    }
                    SendModule.SecuritySelectedIndex = ServiceLocator.Current.GetInstance<MainViewModel>().SecuritySelectedIndex;
                    switch (SendModule.SecuritySelectedIndex)
                    {

                        //明文+RN
                        case 1:
                        //明文+RN_MAC
                        case 2:
                        //明文+SID_MAC
                        case 3:
                        //密文+SID
                        case 4:
                        //密文+SID_MAC
                        case 5:
                            if (string.IsNullOrWhiteSpace(SendModule.SessionInitKey))
                            {
                                MessageBox.Show("请先建立应用连接");
                                return;
                            }
                            break;
                        //明文
                        case 0:
                        
                        default:

                            break;
                    }
                    CommState = false;
                    switch (ListBoxType)
                    {
                        case 0:
                            List<string> OADReadSeleceds = GetReadOADSeleced();
                            if (OADReadSeleceds.Count <= 0)
                            {
                                CommState = true;
                                MessageBox.Show("请选择数据项");
                                return;
                            }
                            ReadRequest((ReadMode)RequestMode, OADReadSeleceds, MainViewModel.selectedDevice.DeviceAddress, SendModule.SecuritySelectedIndex);
                            break;
                        case 1:
                            Dictionary<string, string> OADSetSeleceds = await GetSetOADSeleced();
                            if (OADSetSeleceds.Count <= 0)
                            {
                                CommState = true;
                                MessageBox.Show("请选择数据项");
                                return;
                            }
                            //SetRequest(OADSetSeleceds, MainViewModel.selectedDevice.DeviceAddress);
                            await SendModule.SetRequest((SetMode)RequestMode, OADSetSeleceds, MainViewModel.selectedDevice.DeviceAddress, SendModule.SecuritySelectedIndex);
                            break;
                        case 2:
                            
                            OADSetSeleceds =await GetSetOADSeleced();
                            if (OADSetSeleceds.Count <= 0)
                            {
                                CommState = true;
                                MessageBox.Show("请选择数据项");
                                return;
                            }
                            ActionRequest(OADSetSeleceds, MainViewModel.selectedDevice.DeviceAddress, SendModule.SecuritySelectedIndex);
                            break;
                        case 3:
                            await SendModule.Connect(MainViewModel.selectedDevice.DeviceAddress, gWCmdMakeUpService.Select(objectIDService.Select(2))[0].DataValue);
                            break;
                        case 4:
                            DisConnect(MainViewModel.selectedDevice.DeviceAddress);
                            break;
                        default:
                            break;
                    }
                    MainTask?.ContinueWith((t) =>
                   {
                       CommState = true;
                   });
                    SendModule.MainTask?.ContinueWith((t) =>
                    {
                        CommState = true;
                    });
                });
                return command;
            }
        }

        public RelayCommand ReadCommand
        {
            get
            {
                var command = new RelayCommand(() =>
                {

                if (MainViewModel.selectedDevice == null)
                {
                    MessageBox.Show("请选择设备");
                    return;
                }
                if (!MainViewModel.state)
                {
                    MessageBox.Show("请先打开通道");
                    return;
                }
                SendModule.SecuritySelectedIndex = ServiceLocator.Current.GetInstance<MainViewModel>().SecuritySelectedIndex;
                switch (SendModule.SecuritySelectedIndex)
                {

                    //明文+RN
                    case 1:
                    //明文+RN_MAC
                    case 2:
                    //明文+SID_MAC
                    case 3:
                    //密文+SID
                    case 4:
                    //密文+SID_MAC
                    case 5:
                        if (string.IsNullOrWhiteSpace(SendModule.SessionInitKey))
                        {
                            MessageBox.Show("请先建立应用连接");
                            return;
                        }
                        break;
                    //明文
                    case 0:

                    default:

                        break;
                }
                CommState = false;
                List<string> OADReadSeleceds = GetReadOADSeleced();
                if (OADReadSeleceds.Count <= 0)
                {
                    CommState = true;
                    MessageBox.Show("请选择数据项");
                    return;
                }
                    
                ReadRequest((ReadMode)RequestMode, OADReadSeleceds, MainViewModel.selectedDevice.DeviceAddress, SendModule.SecuritySelectedIndex);
                MainTask.ContinueWith((t) =>
                {
                    CommState = true;
                });
                }
                );
                return command;
            }
        }
        public RelayCommand ReadESAMCommand
        {
            get
            {
                var command = new RelayCommand(() =>
                {
                    if (MainViewModel.selectedDevice == null)
                    {
                        MessageBox.Show("请先选择设备");
                        return;
                    }
                    CommState = false;
                    List<string> OADSeleced = new List<string>();
                    OADSeleced.Add("F1000200");
                    OADSeleced.Add("F1000400");
                    OADSeleced.Add("F1000700");
                    OADSeleced.Add("F1000A00");
                    /*OADSeleced.Add("F1000C00");*/
                    ReadRequest(ReadMode.GetRequestNormalList, OADSeleced, MainViewModel.selectedDevice.DeviceAddress, ServiceLocator.Current.GetInstance<MainViewModel>().SecuritySelectedIndex);
                    /*string OADs = "";
                    OADs += "F1000200";
                    OADs += "F1000400";
                    OADs += "F1000700";
                    byte[] b = MessageGeneration("002001257178", ReadMode.GetRequestNormalList, OADs, false);
                    sendMessageShow(b);

                    serialPortHelper.SendDataMethod(b);*/
                    MainTask.ContinueWith((t) =>
                    {
                        CommState = true;
                    });
                });
                return command;
            }
        }
        public RelayCommand CancelCommCommand
        {
            get
            {
                var command = new RelayCommand(() =>
                {
                    cts?.Cancel();
                    SendModule.cts?.Cancel();
                    Messenger.Default.Send<string>($"正在停止通讯...({DateTime.Now.ToString()})\r\n", "StopMessage");
                });
                return command;
            }
        }
        public override void Cleanup()
        {
            base.Cleanup();
            SimpleIoc.Default.Unregister<GWCmdMakeUp>();
            SimpleIoc.Default.Unregister<ModeBitViewModel>();
            SimpleIoc.Default.Unregister<AddCollectArViewModel>();
            SimpleIoc.Default.Unregister<AddCollectArExtendViewModel>();
        }
        /// <summary>
        /// ModeBit参数设置
        /// </summary>
        public RelayCommand<int> MouseDoubleClickCommand
        {
            get
            {
                var command = new RelayCommand<int>((index) =>
                {
                    if (index < 0)
                    {
                        return;
                    }
                    GWCmdMakeUp gWCmdMakeUpSelected = gWCmdMakeUps[index];
                    switch (gWCmdMakeUpSelected.SubItemName)
                    {
                        case "电能表跟随上报模式字":
                        case "周休日特征字":
                        case "有功组合方式特征字":
                        case "无功组合方式1特征字":
                        case "无功组合方式2特征字":
                        case "主动上报模式字":
                        case "文件属性":
                        case "采集标志":
                        case "开关量接入标志":
                        case "开关量属性标志":
                        case "时段功控投入标识":
                        case "每周限电日":
                        case "确认电能表跟随上报状态字":
                            Cleanup();

                            SimpleIoc.Default.Register(() => gWCmdMakeUpSelected);
                            SimpleIoc.Default.Register<ModeBitViewModel>();

                            ModeBitWindow modeBitWindow = new ModeBitWindow();
                            if (modeBitWindow.ShowDialog() == true)
                            {
                                gWCmdMakeUpService.Update(ModeBitViewModel.GWCmdMakeUp);
                                SetDataList[index].DataValue = ModeBitViewModel.GWCmdMakeUp.DataValue;
                            }
                            break;
                        case "第一套定值":
                        case "第二套定值":
                        case "第三套定值":
                            SimpleIoc.Default.Unregister<GWCmdMakeUp>();
                            SimpleIoc.Default.Unregister<PowerCtrlParamViewModel>();
                            SimpleIoc.Default.Register(() => gWCmdMakeUpSelected);
                            SimpleIoc.Default.Register<PowerCtrlParamViewModel>();

                            PowerCtrlParamView powerCtrlParamView = new PowerCtrlParamView();
                            if (powerCtrlParamView.ShowDialog() == true)
                            {
                                gWCmdMakeUpService.Update(ModeBitViewModel.GWCmdMakeUp);
                                SetDataList[index].DataValue = ModeBitViewModel.GWCmdMakeUp.DataValue;
                            }
                            break;
                        case "通信参数":
                            SimpleIoc.Default.Unregister<GWCmdMakeUp>();
                            SimpleIoc.Default.Unregister<ProxyTransmitCommViewModel>();
                            SimpleIoc.Default.Register(() => gWCmdMakeUpSelected);
                            SimpleIoc.Default.Register<ProxyTransmitCommViewModel>();

                            ProxyTransmitCommView proxyTransmitCommView = new ProxyTransmitCommView();
                            if (proxyTransmitCommView.ShowDialog() == true)
                            {
                                gWCmdMakeUpSelected.DataValue = ProxyTransmitCommViewModel.commControl;
                                gWCmdMakeUpService.Update(gWCmdMakeUpSelected);
                                SetDataList[index].DataValue = ProxyTransmitCommViewModel.commControl;
                            }
                            break;
                        default:
                            break;
                    }
                    if ((gWCmdMakeUpSelected.ObjectIdentifier.Equals("60007F00") || gWCmdMakeUpSelected.ObjectIdentifier.Equals("60008100") || gWCmdMakeUpSelected.ObjectIdentifier.Equals("60008400")) && gWCmdMakeUpSelected.OpenrateType.Equals("7"))
                    {
                        switch (gWCmdMakeUpSelected.SubItemName)
                        {
                            case "基本信息":
                                Cleanup();
                                SimpleIoc.Default.Register(() => gWCmdMakeUpSelected);
                                SimpleIoc.Default.Register<AddCollectArViewModel>();
                                AddCollectArView addCollectArView = new AddCollectArView();
                                if (addCollectArView.ShowDialog() == true)
                                {
                                    gWCmdMakeUpService.Update(AddCollectArViewModel.GWCmdMakeUp);
                                    SetDataList[index].DataValue = AddCollectArViewModel.GWCmdMakeUp.DataValue;
                                }
                                break;
                            case "扩展信息":
                                Cleanup();
                                SimpleIoc.Default.Register(() => gWCmdMakeUpSelected);
                                SimpleIoc.Default.Register<AddCollectArExtendViewModel>();
                                AddCollectArExtendView addCollectArExtendView = new AddCollectArExtendView();
                                if (addCollectArExtendView.ShowDialog() == true)
                                {
                                    gWCmdMakeUpService.Update(AddCollectArExtendViewModel.GWCmdMakeUp);
                                    SetDataList[index].DataValue = AddCollectArExtendViewModel.GWCmdMakeUp.DataValue;
                                }
                                break;
                            default:
                                break;
                        }

                    }
                });
                return command;
            }
        }

        
        #endregion
    }
}
